Before studying this article, there is one pre-requisite you should do. You should learn Properties in C#.
What is Indexer in C# ?
Indexer is an extended version of Properties in C#. It is an array of properties.
Things to remember before using Indexer
- Remove all the private variables within class and take a single variable which act as property.
- There is no name for Indexer unlike properties in C#.
- Indexer is referred by “this”.
Program for Indexer in C#
using System;
class Candidate
{
object[] data = new object[2];
public object this[int i]
{
get{ return data[i];}
set{data[i] = value;}
}
}
class Hr
{
public static void Main()
{
Candidate shubham = new
Candidate();
shubham[0] = “B.Tech”;
shubham[1] = 23;
Console.WriteLine(“Qualification of shubham is “+shubham[0]);
Console.WriteLine(“Age of shubham is “+shubham[1]);
}
}
Output:
Qualification of shubham is B.Tech
Age of shubham is 23