AspBucket offers ASP.NET, C#, VB, Jquery, CSS, Ajax, SQL tutorials. It is the best place for programmers to learn

Tuesday, 5 June 2018

What are Indexers in C#?

In current article I am going to discuss How to implement Indexers? Indexer is an object which is virtually behaving as an array. Where declaration on indexer is similar to properties & get and set accessors  are use to define an indexer.
Syntax Declaration

access-specifier this[int index] {
   
   get {
      // return the value specified by index
   }  
   
   set {
      // set the value specified by index
   }
}

Indexer are defined by "this" keyword. Which refers as an object reference. Please check below example for indexer.


using System;

namespace SampleIndexerApp {
   
   class IndexedData {
      private string[] datalist = new string[size];
      static public int size = 5;
      
      public IndexedData() {
         for (int i = 0; i < size; i++)
         datalist[i] = "";
      }

      public string this[int index] {
         get {
            string tmp;
         
            if( index >= 0 && index <= size-1 ) {
               tmp = datalist[index];
            } else {
               tmp = "";
            }
            
            return ( tmp );
         }
         set {
            if( index >= 0 && index <= size-1 ) {
               datalist[index] = value;
            }
         }
      }
      static void Main(string[] args) {
         IndexedData names = new IndexedData();
         names[0] = "Shivam";
         names[1] = "Ram";
         names[2] = "Subhagya";
         names[3] = "Vinod";
         names[4] = "Hari";
         
         
         for ( int i = 0; i < IndexedData.size; i++ ) {
            Console.WriteLine(names[i]);
         }
         Console.ReadKey();
      }
   }
}

Output Result: Following is the result for above program.
Shivam
Ram
Subhagya
Vinod
Hari

0 comments :

Post a Comment

  • Popular Posts
  • Comments