30

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.

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Michael
  • 3,099
  • 4
  • 31
  • 40

3 Answers3

43

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 { } }
}
Jack Bolding
  • 3,801
  • 3
  • 39
  • 44
27

C# internally creates a property called Item for languages that don't support the indexer. You can control this name using the IndexerNameAttribute, like this:

[IndexerName("MyIndexer")]
public object this[string index]
{
    get { return blah; }
}
Danny Tuppeny
  • 40,147
  • 24
  • 151
  • 275
4

If I remember correctly, such an indexer can be accessed from VB.Net through an "Item()" method. That would be where that "defined twice" comes from.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111