While taking interviews for Microsoft.NET i often ask about indexer classes in C#.NET and i found that most of people are unable to give answer that how we can create a indexer class in C#.NET. We know the array in C#.NET and each element in array can be accessed by index same way for indexer class a object was class can be accessed by index. Its very easy to create a indexer class in C#. First lets looks some points related to indexer class in C#.
- Indexer class object can be accessed by index only.
- We can use same mechanism to access object of indexer class as we are doing it for array.
- You can can specify any valid C# type as return type of indexer classes.
- You must have to create a property with parameter using this keyword for indexer class.
- You can also implement multi parameter indexer also.
Let’s create simple indexer class with single parameter and for string type.
public class MyIndexer
{
private string[] MyIndexerData;
private int SizeOfIndexer;
//declaring cursor to assing size of indexer
public MyIndexer(int sizeOfIndex)
{
this.SizeOfIndexer = sizeOfIndex;
MyIndexerData = new string[SizeOfIndexer];
}
public string this[int Position]
{
get
{
return MyIndexerData[Position];
}
set
{
MyIndexerData[Position] = value;
}
}
}
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int indexSize=5;
MyIndexer objMyIndexer = new MyIndexer(indexSize);
for (int i = 0; i < indexSize; i++)
{
objMyIndexer[i] = i.ToString();
Console.WriteLine("Indexer Object Value-[{0}]: {1}",
i, objMyIndexer[i]);
}
Console.ReadKey();
}
}
}
Technorati Tags: Indexer,C#,Array