Michael Weston Michael Weston - 1 year ago 71
C# Question

Why does an indexer property in a class need a private array field and not just an integer telling the object its index?

I thought the point of indexers was so that if you had an array or list of a certain class in something like a winform, you could just get the index of the object by typing myObject[index].SomeMethod();

Why do examples about indexers in C# need for a class to have a private field of an array, and then the public indexer property gets the index from that private array? Wouldn't it be better to just hold an integer that tells it what its index is? What's the difference?

Answer Source

The class needs to know exactly what the index is referencing.

An integer containing just the index doesn't tell the class what object it's supposed to retrieve with that index, especially if that class isn't itself a collection (but this can be the case even with a collection type depending on its implementation). For example, if myObject is an instance of MyClass and MyClass isn't a collection, what exactly would myObject[index] refer to? The calling code needs to know this (since it expects a return type that contains a SomeMethod() method), but only MyClass can tell the calling code exactly how its indexer works since the indexer is part of its class definition.

In short, think of the indexer as the interface — in fact, you can declare an indexer on an interface:

public interface IFooList
    Foo this[int i] { get; set; }

— and the underlying collection as the implementation.

You don't need a private array field — you could just as easily use a collection that's already being exposed as an auto-implemented public property for example (although this is usually bad practice since now you have two potentially different methods of accessing that collection instead of just one):

public IList<Foo> FooList { get; } = new List<Foo>();

public Foo this[int i]
    get { return FooList[i]; }
    set { FooList[i] = value; }

You could even use something that's not a collection entirely, and write custom logic for the index within the indexer definition. But the point is that the indexer needs to know exactly what to look for.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download