C# introduces a new concept known as 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.
Indexer is a collection of SET and GET methods.
Indexer name must be "this".
One class can have only one indexer.
Indexer Concept is object act as an array.
Indexers in C# must have at least one parameter.
Else the compiler will generate a compilation error.
indexers are never static in C#.
Benefits:-
Indexers always need an object reference to assign or retreive data from arrays or collections.
The following is syntax
{
get
{
// Get codes goes here
}
set
{
// Set codes goes here
}
}
//Example
class IndexerClass
{
private string[] names = new string[10];
public string this[int i]
{
get
{
return names[i];
}
set
{
names[i] = value;
}
}
}
static void Main(string[] args)
{
IndexerClass text = new IndexerClass();
text[0] = "subhash";
text[1] = "subhash1";
text[2] = "subhash2";
for (int i = 0; i < 10; i++)
{
Console.WriteLine(text[i]);
}
Console.ReadKey();
}
No comments:
Post a Comment