Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic class whose parameter extends a nested class

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.

like image 523
silvalli Avatar asked Aug 28 '18 15:08

silvalli


People also ask

Can Java inner class be generic?

So you should not declare twice the generic : in the class and its inner class. The E type is indeed visible in the inner class as inner classes have access to other members of the enclosing class (including the generic of the class).

What is difference between class and generic class?

The generic class works with multiple data types. A normal class works with only one kind of data type.


1 Answers

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.

like image 103
zneak Avatar answered Oct 06 '22 23:10

zneak