Vishful thinking…

Implementing an indexer and an ‘Item’ property on a class

Posted in Uncategorized by viswaug on November 20, 2007

This is more a quick tip than anything else. Today I was trying to create a class with both an indexer and a property named ‘Item’ like below. But I was unable to compile the class with an error message saying “The type ‘Test’ already contains a definition for ‘Item'”.

    public class Test

    {

        public string this[string name]

        {

            get { return null; }

        }

 

        string _item;

        public string Item

        {

            get { return _item; }

            set { _item = value; }

        }

    }

This was due to the fact that the indexer in C# gets converted to a property name ‘Item’ internally in order to support other languages that don’t support indexers. And the ‘Item’ property I was trying to create had a conflict the ‘Item’ property that was getting created internally. However, a quick google search revealed that the problem could be easily circumvented by decorating the indexer with the ‘IndexerNameAttribute’. This forces the compiler to assign a custom name to the auto-created property for the indexer as shown below.

   [System.Runtime.CompilerServices.IndexerName(“MyItem”)]

   public string this[string name]

   {

       get { return null; }

   }

 This post will also serve as a reminder to me because I know I will run across this again in the future …🙂

One Response

Subscribe to comments with RSS.

  1. kichu75 said, on October 19, 2009 at 6:54 pm

    It works. Thanks


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: