C# Indexers
- An Indexer is a special type of property that allows a class or structure to be accessed like an array for its private collection.
- An indexer can be defined the same way as property with this keyword and square brackets [].
- Indexer Concept is object act as an array.
- Indexer an object to be indexed in the same way as an array.
- Indexer modifier can be private, public, protected or internal.
- The return type can be any valid C# types.
- Indexers in C# must have at least one parameter. Else the compiler will generate a compilation error.
Example
class IndexerExample
{
public string[] stringarr = new string[10];
public string this[int index]
{
get
{
return stringarr[index];
}
set
{
stringarr[index] = value;
}
}
public static void Main()
{
IndexerExample ie = new IndexerExample();
ie[0] = "This";
ie[1] = "Is";
ie[2] = "Indexer";
ie[3] = "Example";
Console.WriteLine(ie[0] + " " + ie[1] +" "+ ie[2] + " " + ie[3]);
Console.ReadLine();
}
Output:
This is Indexer Example
No comments:
Post a Comment
Please let me know if you have any feedback or doubts.