Indexers in C#

 

Indexers in C# are same as properties, but used for providing access to private array i.e, defined in a class. Property will have a name but indexer will not have any name. The name of indexer while defining  it will be "this" keyword which makes we are defining the indexer directly on the class itself. So once the indexer is defined inside of class, object of that class starts behaving like an array and provides access to the array values inside it.

 

The syntax to define an Indexer in C#:

 

[<modifier>] <type>  this[int index] 

{ 

[get {<statements>;}] //Get Accessor 

[set {<statements>;}] //Set Accessor 

}

 

Example of Indexer in C# is shown below. 

public class ArrayDemo 

{ 

        //private array cannot be accessed out of the class 

        int[] arr;

        public ArrayDemo(int iSize) 

        { 

            arr = new int[iSize]; 

        }

        //defining an indexer to access array out of the class 

        public int this[int index] 

        { 

            get { return arr[index];}     

 

            set { 

                if (value >= 10) 

                    arr[index] = value; 

            } 

        }

}

tags:

C# indexers