Before reading on with this tutorial, please be sure you have an understanding of the following concepts:
- Brief understanding of properties (indexers share some similarities).
- C# get and set accessors.
- The implicit variable "value".
- The formal parameter list.
Indexers is a feature in C# that allows you to treat an object like an array. By using indexers you have the ability to access members through indexes. Indexers are also known as smart arrays in the C# community. Indexers are basically members that allow an object to be indexed the same way an array.
The format for indexers is as follows:
CODE
<modifier> <return type> this [parameter list]
{
set
{
// Set code.
}
get
{
// Get code.
}
}
The modifier can be: public, private, protected or internal. The return type can be any valid C# type. The
formal parameter list must have atleast on parameter.
ref and
out parameter modifiers are not permitted. It is also not possible to define a static indexer.
Here is a quick example demonstrating the construction of indexers:
CODE
class foo
{
// The field member our indexer will be accessing.
private string[] data = new string[3];
// The indexer.
public string this [int index]
{
set
{
data[index] = value;
}
get
{
return data[index];
}
}
};
Now, our object can be accessed through indexes:
CODE
foo bar = new foo();
bar[0] = "Element 1";
bar[1] = "Element 2";
bar[2] = "Element 3";
Here is another example of indexers, indexing two field members:
CODE
class MyClass
{
private int Field1;
private int Field2;
public int this [int index]
{
get
{
if (index == 0)
return Field1;
else
return Field2;
}
set
{
if (index == 0)
Field1 = value;
else
Field2 = value;
}
}
}
Indexers can be overloaded like any other type of member. To overload an indexer, its signature must differ. The signature of an indexer is constructed from the number and types of its
formal parameters. It isn't sufficient for the indexer type to be different. The parameter lists must be different.
The following is an example of indexer overloading:
CODE
class MyClass
{
public string this [ int index ]
{
get { ... }
set { ... }
}
public string this [ int index1, int index2 ]
{
get { ... }
set { ... }
}
public int this [ float index1 ]
{
get { ... }
set { ... }
}
}
Note the differences between indexers and properties:
- Properties are identified by their names, but an indexer is identified by its signature.
- Indexers are accessed through element access. Properties are accessed through member access.
- Indexers are always an instance member, but properties may be static.