indexers C# If we heard the word indexers or index, the name “Array” will come to our mind. Arrays are accessed by using the index. In the same way in C# also, Indexer is used to access the class instances by means of index notation. |
C# launches a new concept that is called Indexers which are used for treating an object as an array. The indexers are usually known as smart arrays in C# community. Defining a C# indexer is much like defining properties. We can say that an indexer is a member that enables an object to be indexed in the same way as an array. |
Syntax for Declaration: |
<access modifier> <return type> this [argument list] { get { // Get codes goes here } set { // Set codes goes here } } |
Where, the access modifier can be private, public, protected or internal in C#. The return type can be any valid C# types. The ‘this’ is a special keyword in C# to indicate the object of the current class. The formal-argument-list specifies the parameters of the indexer. |
The formal-argument-list of an indexer corresponds to that of a method, except that at least one parameter must be specified, and that the ref and out parameter modifiers are not permitted. Remember that indexers in C# must have at least one parameter. Other wise the compiler will generate a compilation error. |
Simple Example using Indexer in C# |
using System; namespace IndexerExample { Class MyPrevExp { private string[] myCompanies = new string[10]; //index creation public string this[int index] { get { if(index <0 or index >= 6) return "null"; else return myCompanies[index]; } set { if(!(index <0 or index >= 10)) myCompanies[index] = value; } } } Class myMainClass { public static void Main() { myPrevExp indexerObj = new myPrevExp(); indexerObj[0] = "AMS" indexerObj[3] = "HCL" indexerObj[5] = "ACC" for(int i=0; i<10; i++) { Console.WriteLine("My Companies{0}:{1}", i,indexerObj[i]); } } } } |
Here, I have created a class named myPrevExp and having a memeber called myCompanies which is an array of string.The index is created using “this” operator and set and get accessor are same as we use in properties. |
It’s better to know the difference between properties and indexer to have clear idea |
|
Then in Main Class, The Indexer object is created using the indexer myPrevExp which we defined earlier using the following statement: |
myPrevExp indexerObj = new myPrevExp(); |
Now the indexer is created which is having 20 Elements in it. The indexer is accessed through its elemets like: |
indexerObj[0] = "eBIZ.com Pvt. Ltd." indexerObj[3] = "HCL" indexerObj[5] = "ACC" |
Here only first, third and fifth elements are accessed and assigned with string values.because we have created the indexer of type ‘string’. |
If we want to print the indexer using for loop we can see the result as follows. |
myCompanies 0 : eBIZ.com Pvt. Ltd. myCompanies 1 : myCompanies 2 : myCompanies 3 : HCL myCompanies 4 : myCompanies 5 : ACC myCompanies 6 : null myCompanies 7 : null myCompanies 8 : null myCompanies 9 : null |
We notice the above result, element 0, element 3, element 5 are assigned with values and element 6 to 9 are assigned with null values. This is done in the indexer get accessor statement. |
Indexers & Inheritance |
Just like any other class members, indexers can also participate in inheritance. A base class indexer is inherited to the derived class. |
//C#: Indexer: Inheritance using System; class BaseClass { public int this[int indxer] { get { Console.Write("BaseClass GET"); return 10; } set { Console.Write("BaseClass SET"); } } } class DerivedClass : BaseClass { } class MyClient { public static void Main() { DerivedClass d1 = new DerivedClass(); d1[0] = 10; //Displays 'BaseClass SET BaseClass GET 10' Console.WriteLine(d1[0]); } } |
Indexers & Polymorphism |
A Base class indexer can be polymorphicaly overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level. |
//C#: Indexer: Polymorphism using System; class BaseClass { public virtual int this[int index] { get { Console.Write("BaseClass GET"); return 10; } set { Console.Write("BaseClass SET"); } } } class DerivedClass : BaseClass { public override int this[int index] { get { Console.Write("DerivedClass GET"); return 10; } set { Console.Write("DerivedClass SET"); } } } class MyClient { public static void Main() { BaseClass b1 = new DerivedClass(); b1[0]= 10; //Displays 'DerivedClass SET DerivedClass GET 10' Console.WriteLine(b1[0]); } } |
Abstract Indexers |
An indexer within a class can be declared as abstract by using the abstract keyword. Remember that an abstract indexer within a class carries no code at all. The get/set accessors are simply represented with a semicolon. We must implement both set and get assessors in the derived class. |
If the abstract class contains only set accessor, we can implement only set in the derived class. |
The following program shows an abstract indexer in action. |
//C#: Indexer: Abstract using System; abstract class AbstractClass { public abstract int this[int index] { get; set; } } class Concrete : AbstractClass { public override int this[int index] { get { Console.Write(" GET"); return 10; } set { Console.Write(" SET"); } } } class MyClient { public static void Main() { Concrete c1 = new Concrete(); c1[0] = 10; //Displays 'SET GET 10' Console.WriteLine(c1[0]); } } |
Comparison between Properties and Indexers |
Indexers permit instances of a class or struct to be indexed in the same way as arrays. Indexers are similar to properties. Except for the differences shown in the given below, all of the rules defined for property accessors apply to indexer accessors as well. |
Property: |
? Identified by its name.
? Accessed through a simple name or a member access. ? Can be a static or an instance member. ? A get accessor of a property has no parameters. ? A set accessor of a property contains the implicit value parameter. |
Indexer: |
? Identified by its signature.
? Accessed through an element access. ? Must be an instance member. ? A get accessor of an indexer has the same formal parameter list as the indexer. ? A set accessor of an indexer has the same formal parameter list as the indexer, in addition to the value parameter. |
Practical Example (Indexer): |
testIndexer.cs |
using System; using System.Collections.Generic; using System.Text; namespace testIndexer { class MyPrevExp { private string[] myCompanies = new string[10]; //index creation public string this[int index] { get { if(index <0 || index >= 6) return "null"; else return myCompanies[index]; } set { if(!(index <0 || index >= 10)) myCompanies[index] = value; } } } class Program { public static void Main(string[] args) { testIndexer.MyPrevExp indexerObj = new testIndexer.MyPrevExp(); indexerObj[0] = "eBIZ.com Pvt. Ltd."; indexerObj[3] = "HCL"; indexerObj[5] = "ACC"; for(int i=0; i<10; i++) { Console.WriteLine("My Companies{0}: {1}", i,indexerObj[i]); } Console.ReadLine(); } } } |
The Output is: |
![]() |
To Download Indexers example Click here. |
To view downloaded examples, Please Ensure that .NET Framework is installed on your system. |