The utility is to provide a syntax to access, through the index, items of an object representing a collection.
Say you create a class specializing in keeping a collection of cars and you want to get a car through your index in the collection.
If indexers were not available, you would publish a function in your class, for example getaway, and to get an item the consumer would have to do something like this:
Carro carro = carros.getItem(1);
Using indexers, you can write the code of getaway in the format of an indexer, and then the consumer can get an item like this:
Carro carro = carros[1];
If your class represents a collection in a similar way to what is accomplished by a array, it is natural that you want to access the items the same way you do when using a array - this is the function of indexers in C#.
Thus, indexers are just an option to offer a certain syntax to consumers in their class that represents a collection. If there were no indexers you could do otherwise (publish a function getaway, for example).
This feature was widely used before . Net Framework provided collections Generics. At that time we had to create a new class each time we wanted a collection specialized in a particular type and using indexers allowed us to offer the same syntax offered by the framework’s native collections.
As for performance, it makes no difference whether or not to use indexers.
A question @Caffé , this
getItem(1)
would be a function to 'fetch' the item manually?– rubStackOverflow
So indexers serve only to call an item that is within a collection by its index. There is no gain in using indexers?
– MeuChapeu
Yeah, @Hstackoverflow. But note that using indexers doesn’t free you from manually implementing the function that delivers the item - indexers only allow you to provide another syntax for the consumer to access these items. One way or another you will have to write in your class the code that delivers the item. That’s right, Meuchapeu. The gain is in offering a nice syntax - no other gain.
– Caffé