C#: Fun with Indexers

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;

    public string Item { get; set; }
    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:

public int this[int index]
    get { return someList[index]; }
    set { someList[index] = value; }


Posted in Dotnet. Tags: , , . 6 Comments »

6 Responses to “C#: Fun with Indexers”

  1. odecey Says:

    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 =).

  2. DotNetShoutout Says:

    C#: Fun with Indexers « Mehroz’s Experiments…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

  3. dave Says:

    odecey: Just look at the compiled code in the reflector, is ildasm it. You can see what voodoo the compiler do do.

  4. Cato Says:

    To compound the error further, create a class with the name of Item – without the attribute you can’t create any indexers at all!

  5. Pankaj Singh Says:

    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..

    Thanks Everyone!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: