Class with indexer and property named "Item"

Michael picture Michael · Feb 24, 2011 · Viewed 15.4k times · Source

Is it possible to create a class in .NET 4 with:

  1. an indexer,
  2. a property named "Item"?

For example, this C# class will not compile for me:

public class MyClass
{
    public object Item { get; set; }
    public object this[string index] { get { return null; } set { } }
}

The compiler gives an error CS0102:

The type 'MyClass' already contains a definition for 'Item'

although I am only explicitly defining Item once.

Answer

Jack Bolding picture Jack Bolding · Feb 24, 2011

Based on this site, it is possible to use an attribute to rename the Indexer

public class MyClass
{
    public object Item { get; set; }
    [System.Runtime.CompilerServices.IndexerName("MyItem")]
    public object this[string index] { get { return null; } set { } }
}