Introduction
Indexer:
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.
Syntax for Declaration:
public type this [type identifier]
Ex : public string this [int myIndex]
Declaring Indexer
public string this[int myCompanies]
{
get{
return mycompanies[index]
}
set{
}
}
Simple Example using Indexer in C#
using System;<BR><BR><BR>namespace IndexerExample<BR>{<BR><BR>Class MyPreviousExp<BR>{ <BR> private string[] myCompanies = new string[10]; <BR><BR>
Description:
Here i have created a class named myPreviousExp and having a memeber called myCompanies which is
a array of string.The index is created using the this operator and set and get accessor are same
as we use in properties.
Better to know the difference between properties and indexer to have clear idea
property can have unique name whereas the indexer can have uniuqe signature.
Prperty is accessed through its name(like obj.mycolor: here mycolor is property)
whereas Indexer is accessed through an element (obj[1] = "abc" : here we are assigning abc to the first element of indexer)
Then in Main Class, The Indexer object is created using the indexer myPreviousExp which we defined earlier using the following statement
myPreviousExp indexerObj = new myPreviousExp();
Now the indexer is created which is having 20 Elements in it. The indexer is accessed through its elemets like
indexerObj[0] = "AMS"
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.
In next step, if we print the indexer using the for loop we can see the result as follows.
myCompanies 0 : AMS
myCompanies 1 :
myCompanies 2 :
myCompanies 3 : HCL
myCompanies 4 :
myCompanies 5 : ACC
myCompanies 6 : null
myCompanies 7 : null
myCompanies 8 : null
myCompanies 9 : null
If we notice the above result, element 0,element 3,element 5 are assigned with values and element 6 to 9 are assigned with
null vaules.This is done in the indexer get accessor statement.
Summary
About Indexer
.Gives the Array like access to class instances and members
.Indexer can be overloaded
Hope this tutorilal will help you understand about indexer in C#
any queries reach me in arul_tony@yahoo.com
Working as a Software Engineer in a MNC Company.Knowledge on C#.NET, ASP.NET, VB.NET ,VB & SQL Server.