Tuesday, March 20, 2007

The Indexer Name

Any guesses why the following class won't compile?

public class SuperSimpleIndexerClass
{
__public double this[int index]
__{
____get { return 0; }
__}

__public double Item
__{
____get { return 0; }
__}
}


It has to do with the way indexers are internally represented in C#. By default, indexers have the name "Item." Thus, the indexer property and the explicit Item property will have a naming collision. We can fix this problem by providing the following attribute.

public class SuperSimpleIndexerClass
{
__[System.Runtime.CompilerServices.IndexerName("TheItem")]
__public double this[int index]
__{
____get { return 0; }
__}

__public double Item
__{
____get { return 0; }
__}
}


Now, this indexer will have the name TheItem.