What is Indexer and why we use in C#.
C# has introduced a new concept Indexer.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 at runtime error. Indexers are always created with this keyword.Indexers are implemented through the get and set accessors for the [ ] operator.
Syntax-----
Public <return type> this[<parameter type> index]
{
Get
{
// return the value from the specified index
}
Set
{
// set values at the specified index
}
}
Example.
using System;
using System.Collections;
class MyClass
{
private string[] data = new string[5];
public string this[int index]
{
get
{
return data[index];
}
set
{
data[index] = value;
}
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc[0] = "Rakesh";
mc[1] = "A3-126";
mc[2] = "shambhu";
mc[3] = "Pappu";
mc[4] = "Mumbai";
Console.WriteLine("{0},{1},{2},{3},{4}", mc[0], mc[1], mc[2], mc[3], mc[4]);
Console.Read();
}
}
output:
Syntax-----
Public <return type> this[<parameter type> index]
{
Get
{
// return the value from the specified index
}
Set
{
// set values at the specified index
}
}
Example.
using System;
using System.Collections;
class MyClass
{
private string[] data = new string[5];
public string this[int index]
{
get
{
return data[index];
}
set
{
data[index] = value;
}
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc[0] = "Rakesh";
mc[1] = "A3-126";
mc[2] = "shambhu";
mc[3] = "Pappu";
mc[4] = "Mumbai";
Console.WriteLine("{0},{1},{2},{3},{4}", mc[0], mc[1], mc[2], mc[3], mc[4]);
Console.Read();
}
}
output:


0 Comments