INDEXER in C#

Through this article you will learn the concept of INDEXER in C#.

INDEXER IN C#

 
 
C# introduces a new concept Indexer. This is very useful for some situation. Let as discuss something about Indexer.
  • Indexer Concept is object act as an array.
  • Indexer an object to be indexed in the same way as an array.
  • Indexer modifier can be private, public, protected or internal.
  • The return type can be any valid C# types.
  • Indexers in C# must have at least one parameter. Else the compiler will generate a compilation error.
  1. this [Parameter]  
  2. {  
  3.     get  
  4.     {  
  5.         // Get codes goes here  
  6.     }  
  7.     set  
  8.     {  
  9.         // Set codes goes here  
  10.     }  
  11. }  
For Example
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4.   
  5. namespace Indexers  
  6. {  
  7.     class ParentClass  
  8.     {  
  9.         private string[] range = new string[5];  
  10.         public string this[int indexrange]  
  11.         {  
  12.             get  
  13.             {  
  14.                 return range[indexrange];  
  15.             }  
  16.             set  
  17.             {  
  18.                 range[indexrange] = value;  
  19.             }  
  20.         }  
  21.     }  
  22.     /* The Above Class just act as array declaration using this pointer */  
  23.     class childclass  
  24.     {  
  25.         public static void Main()  
  26.         {  
  27.             ParentClass obj = new ParentClass();  
  28.             /* The Above Class ParentClass  create one object name is obj */  
  29.             obj[0] = "ONE";  
  30.             obj[1] = "TWO";  
  31.             obj[2] = "THREE";  
  32.             obj[3] = "FOUR ";  
  33.             obj[4] = "FIVE";  
  34.             Console.WriteLine("WELCOME TO C# CORNER HOME PAGE\n");  
  35.             Console.WriteLine("\n");  
  36.             Console.WriteLine("{0}\n,{1}\n,{2}\n,{3}\n,{4}\n", obj[0], obj[1], obj[2], obj[3], obj[4]);  
  37.             Console.WriteLine("\n");  
  38.             Console.WriteLine("ALS.Senthur Ganesh Ram Kumar\n");  
  39.             Console.WriteLine("\n");  
  40.             Console.ReadLine();  
  41.         }  
  42.     }  
  43. }