Indexers are simple components of C#. Suppose an array exits in a particular class. To access the elements of the array,you would actually have to mention the array name after the object name, then specify the index value of the array and finally assign value. Now with c#, an indexers for an array can be created and access to the elements of the array is obtained directly by specifying the index from the class object. Indexers allow an object to be indexed in the same way as an array.Indexers provide field-like access to the data of an object, Indexers enable array-like access to the members of the classes. Example:
class IndexersTest { public int[] list=new int[10]; public int this[int index] { get { return list[index]; } set { list[index]=value; } } } class Test { static void Main() { IndexersTest IndexMe = new IndexersTest(); IndexMe .list[1]=5; IndexMe [2]=10; System.Console.WriteLine("IndexMe[1] is {0}\nIndexMe[2] is {1}", IndexMe [1], IndexMe [2]); } }
The output of the above example is as follows: IndexMe [1] is 5 IndexMe [2] is 10
In the above example, in class IndexerTest there exists is property called this. This is the indexer. Indexers must always be named as this since they are accessed using the object they belong to.
Declaring an indexer is quite similar to defining a property. The steps to be followed while defining an indexers are as follows: 1. First the access modifier that decides the visibility of the indexer, needs to be mentioned. 2. This should be followed by the return type of the indexer (what the get accessor returns). 3. Then the Keyword this is specified (this is the name if the indexer, it should be always be this). 4. This is followed by the open square brackets. 5. The data type of the index ( indexers unlike array, can also be indexed on string or any other data type) follows. 6. Subsequently, the variable name for the index is specified followed by closed square bracket. 7. Finally, the open curly braces are applied. The get and set accessors are specified here, just as in the case of properties. This is followed by the closed braces.
Rules for defining an indexer: 1. At least one indexer parameter must be specified. 2. The parameter should assigned values. This means that the indexer must have at least one indexer parameter, that is at least one variable within the Square Brackets.
Note: 1. Indexers do not point to memory location. 2. indexers can have non-integer subscripts (indexes) 3. Indexers can be overloaded.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|