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 … 🙂

Advertisements