An Indexer is a special type of property that allows a class or structure to be accessed the same way as array for its internal collection. It is same as property except that it defined with this keyword with square bracket and parameters.
Example:
class StringDataStore
{
private string[] strArr = new string[10]; // internal data storage
public string this[int index]
{
get
{
if (index < 0 && index >= strArr.Length)
throw new IndexOutOfRangeException("Cannot store more than 10 objects");
return strArr[index];
}
set
{
if (index < 0 || index >= strArr.Length)
throw new IndexOutOfRangeException("Cannot store more than 10 objects");
strArr[index] = value;
}
}
}
Example:
class StringDataStore
{
private string[] strArr = new string[10]; // internal data storage
public string this[int index]
{
get
{
if (index < 0 && index >= strArr.Length)
throw new IndexOutOfRangeException("Cannot store more than 10 objects");
return strArr[index];
}
set
{
if (index < 0 || index >= strArr.Length)
throw new IndexOutOfRangeException("Cannot store more than 10 objects");
strArr[index] = value;
}
}
}