Indexer :

May 11, 2011
  • An indexer allows programmer to create classes that can act like VIRTUAL ARRAYS.
  • We can access instances of those classes using the [] array access operator.
  • Defining an indexer in C#.net is similar to defining operator [] in C++, but it is considerably more flexible in .Net.
  • An indexer can have private, public, protected or internal modifier & the return type can be any valid C# types.
  • Use of an indexer allows the user or programmer of that class which encapsulate array or collection like functionality to use the array syntax to access the class.
  • An Indexer in C#.Net must have at least one parameter otherwise the compiler will throw a compilation error.
class Codekey_Indexer_Class { private int[] expArray = new int[50]; public int this[int index] { get { if (index < 0 || index >= 50) return 0; else return expArray[index]; } set { if (!(index < 0 || index >= 50)) expArray[index] = value; } } } public class Codekey_Main_Class { public static void Main(string[] args) { Codekey_Indexer_Class b = new Codekey_Indexer_Class(); b[3] = 420; b[5] = 840; for (int k = 1; k <= 5; k++) { Console.WriteLine("Value of #{0} is = {1}", k, b[k]); } } }

Output:
Value of #1 is = 0
Value of #2 is = 0
Value of #3 is = 420
Value of #4 is = 0
Value of #5 is = 840