How useful are indexers?

6

I was watching and Csharp has indexers. Second definition on the microsoft: site

  

Indexers allow instances of a class or structure   are indexed only as vectors.

Examples:

internal class Indexador<T>
{
    private T[] array = new T[100];

    public T this[int i]
    {
        get { return array[i]; }
        set { array[i] = value; }
    }
}

Indexador<string> index = new Indexador<string>();
index[0] = "string na posicao 0";

And my doubts are:

  • What is the real use of indexers?
  • Is there any gain in performance or something?
  • In which cases would it be recommended to use crawlers?
asked by anonymous 27.05.2015 / 19:46

1 answer

7
  

The utility is to provide a syntax for accessing, through the index, items of an object that represents a collection.

Let's say you create a class that specializes in keeping a collection of cars and you want to get a car through its index in the collection.

If indexers were not available, you would publish in your class a function, for example getItem , 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 getItem code 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 similar to what is done by an array , it is only natural that you want to access the items the same way you do when you use an array - this is the function of indexers in C #.

  

Thus, indexers are just an option to offer a certain syntax to consumers in your class that represent a collection. If there were no indexers you could do it another way (publish a getItem function, for example).

This feature was widely used before the .Net Framework provided generics collections. At that time we had to create a new class every time we wanted a specialized collection on a particular type and using indexers allowed us to offer the same syntax offered by the native framework collections.

As for performance, it makes no difference whether to use indexers.

    
27.05.2015 / 20:06