What is the use of indexers?

Asked

Viewed 308 times

6

I was watching and the Csharp has indexes. Second definition on the website microsoft:

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 actual use of indexers?
  • Is there any gain deperformance or something like?
  • In which cases, it would be recommended to use indexers?

1 answer

7


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?

  • So indexers serve only to call an item that is within a collection by its index. There is no gain in using indexers?

  • 2

    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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.