Chapter 16
Indexers
Indexers enable AN object to be treated as AN array. They’re declared within the same means as properties, except that the keyword is employed rather than a reputation and their accessors take parameters. Within the example below, the skilled worker corresponds to AN object array referred to as knowledge that the style of the skilled worker is ready to object.
class MyArray
{
object[] knowledge = new object[10];
public object this[int i]
set
}
}
The get accessor returns the desired part from the article array, and therefore the set accessor inserts the worth into the desired part. With the skilled worker in situ AN instance of this category may be created ANd used as an array, each to induce and set the weather.
static void Main()
object o = a[5]; //{hello|hullo|hi|howdy|how-do-you-do|greeting|salutation">hi World}
Indexer parameters
The parameter list of A skilled worker is comparable thereto of a technique, except that it should have a minimum of one parameter which the official or out modifiers aren't allowed. For instance, if there's a two-dimensional array, the column and row indexes may be passed as separate parameters.
class MyArray
{
object[,] knowledge = new object[10,10];
public object this[int i, int j]
{
get come back data[i,j]; } set
}
}
The index parameter doesn't have to be of a whole number kind. AN object will even as somewhat be passed because the index parameter. The get accessor will then be accustomed come back the index position wherever the past object is found.
class MyArray
{
object[] knowledge = new object[10];
public int this[object o]
{
get come back System.Array.IndexOf(data, o); }
}
}
Indexer overloading
Both of those functionalities may be provided by overloading the skilled worker. The kind and variety of arguments can then verify that skilled worker gets referred to as.
class MyArray
{
object[] knowledge = new object[10];
public int this[object o]
{
get come back System.Array.IndexOf(data, o); }
}
public object this[int i]
{
get come back data[i]; } set
}
}
Keep in mind that during a real program a spread check ought to be enclosed within the accessors, thus on avoid exceptions caused by making an attempt to travel on the far side the length of the array.
public object this[int i]
zero && i < knowledge.Length) ? data[i] : null;
}
Set zero && i < knowledge.Length) data[i] = value;
}
}