9

This C# doesn't compile:

public class IdList<T> where T : IdList<T>.Item {
  List<T> List = new List<T>();

  public T this[int id] {
    get => List[id];
    set { }
  }

  public class Item {
    public int id;
    // Not shown: id used for equality and hash.
  }
}

The complaint from the compiler is:

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

If I comment out the indexer, it compiles.

How can I get this to compile? Rider doesn't have a fixit.

The unstylish workaround is not to nest the Item class.

IDE is Rider 2018.1.4, Language level 7.2, on macOS.

3
  • 1
    Interestingly, rename inner class Item to Foo...
    – spender
    Commented Aug 28, 2018 at 15:37
  • 1
    Upvote for teaching me about one of dotnet's dirty little secrets!
    – spender
    Commented Aug 28, 2018 at 15:42
  • I'm intrigued by your use case. Why would you structure a class like this? Maybe it's still to early in the morning for me to suss out what you are trying to accomplish. But, yeah, indexers introduce a magic property named "Item", work around that and you should be golden
    – Flydog57
    Commented Aug 28, 2018 at 15:44

2 Answers 2

6

The issue is that the indexer, when compiled to .NET byte code, becomes a property called "Item". You need to change your type name to something else.

2
1

Solution: eliminate the name collision by using, for example, System.Runtime.CompilerServices.IndexerName("TheItem")

public class IdList<T> where T : IdList<T>.Item {
  List<T> List = new List<T>();

  [System.Runtime.CompilerServices.IndexerName("TheItem")]
  public T this[int id] {
    get => List[id];
    set { }
  }

  public class Item {
    public int id;
    // Not shown: id used for equality and hash.
  }
}

The compiler error should be more explicit and say that Item is already defined as the default name (which can be overridden) for the indexer, and the IDE should offer this fixit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.