An indexer allows an instance of a class or struct to be indexed as an array. If the user will define an indexer for a class, then the class will behave like a virtual array. Array access operator i.e ([ ]) is used to access the instance of the class which uses an indexer. A user can retrieve or set the indexed value without pointing an instance or a type member. Indexers are almost similar to the Properties. The main difference between Indexers and Properties is that the accessors of the Indexers will take parameters.
Syntax:
[access_modifier] [return_type] this [argument_list] { get { // get block code } set { // set block code } }
In the above syntax:
- access_modifier: It can be public, private, protected or internal.
- return_type: It can be any valid C# type.
- this: It is the keyword which points to the object of the current class.
- argument_list: This specifies the parameter list of the indexer.
- get{ } and set { }: These are the accessors.
Example:
// C# program to illustrate the Indexer using System; // class declaration class IndexerCreation { // class members private string[] val = new string[3]; // Indexer declaration // public - access modifier // string - the return type of the Indexer // this - is the keyword having a parameters list public string this[int index] { // get Accessor // retrieving the values // stored in val[] array // of strings get { return val[index]; } // set Accessor // setting the value at // passed index of val set { // value keyword is used // to define the value // being assigned by the // set indexer. val[index] = value; } } } // Driver Class class main { // Main Method public static void Main() { // creating an object of parent class which // acts as primary address for using Indexer IndexerCreation ic = new IndexerCreation(); // Inserting values in ic[] // Here we are using the object // of class as an array ic[0] = "C"; ic[1] = "CPP"; ic[2] = "CSHARP"; Console.Write("Printing values stored in objects used as arrays\n"); // printing values Console.WriteLine("First value = {0}", ic[0]); Console.WriteLine("Second value = {0}", ic[1]); Console.WriteLine("Third value = {0}", ic[2]); } }
Output:
Printing values stored in objects used as arrays First value = C Second value = CPP Third value = CSHARP
Recent Comments