This post refers to an interesting situation when you create a class in C# with an indexer and a property named “Item”. Let’s see why this is not possible simultaneously.
Few days back, I got an interesting error. I had a class with a property named Item and an indexer like this:
public class SomeClass
{
List<int> someList;
//property
public string Item { get; set; }
//indexer
public int this[int index]
{
get { return someList[index]; }
set { someList[index] = value; }
}
}
Nothing special? But when I tried to compile, it complained saying:
The type 'MyNamespace.DataClasses.SomeClass' already contains a definition for 'Item'.
Strange!! and the location of the error as pointed by Visual Studio was my indexer:
Well, the reason is that internally, C# converts the indexer to a property name ‘Item’ to be able to support other languages that don’t directly support indexers. Since I had already defined a property name Item, so a conflict was created. Luckily, this can be solved by forcing the compiler to use a custom name other than ‘Item’ by using the IndexerNameAttribute. So, here’s a quick fix for such situation:
[IndexerName("Indexer")]
public int this[int index]
{
get { return someList[index]; }
set { someList[index] = value; }
}
Enjoy!!!

December 30, 2010 at 4:52 AM
That’s very useful to know. I don’t know if I’d be able to find the source of an error like that, would you mind elaborating on how you debugged this?
Thanks for sharing in any case =).
December 30, 2010 at 9:25 AM
C#: Fun with Indexers « Mehroz’s Experiments…
Thank you for submitting this cool story – Trackback from DotNetShoutout…
December 30, 2010 at 3:50 PM
[...] C#: Fun with Indexers – syed [...]
January 4, 2011 at 8:14 PM
odecey: Just look at the compiled code in the reflector, is ildasm it. You can see what voodoo the compiler do do.
January 27, 2011 at 4:44 AM
To compound the error further, create a class with the name of Item – without the attribute you can’t create any indexers at all!
November 16, 2011 at 9:05 PM
This is one of the best articles I read online. No crap, just useful information. Very well presented. I have found another nice post over internet related to this post. You may check it by visiting following link..
http://mindstick.com/Blog/103/Indexer%20in%20C
Thanks Everyone!!