richardtallent
richardtallent

Reputation: 35374

How can I reference the inner generic type of a generic type in C#

Consider this generic class:

class TList<T> : System.Collections.Generic.List<T> {
}

I have another generic list class that contains these lists and may need to work on their members:

class TListList<U, T> : System.Collections.Generic.List<U> where U : TList<T>
{
   public void Foo() {
      foreach(U list in this) {
        T bar = list[0];
      }
   }
}

And here's a concrete implementation:

class FooList : TList<Foo> {}
class FooListList : TListList<FooList, Foo> {}

What I'd like to do is drop the T type parameter in the specification of TListList and have the compiler notice it in the where clause and make it available to the members of TListList:

class TListList<U> where U : TList<T> { ...same Foo() as above... }

class FooList : TList<Foo> {}
class FooListList : TListList<FooList> {}

Is this possible and I'm just going about it the wrong way, or is the language just not capable of this?

Upvotes: 0

Views: 165

Answers (1)

cdhowie
cdhowie

Reputation: 169018

No, this is not possible. Each distinct generic type must be declared ahead of time -- you can't omit T in the list <U, T>, because then T is an undeclared identifier.

(Also, I'm sure you know this, but inheriting from List<> is a very bad thing to do. Implement IList<> instead, and delegate to an implementation.)

Upvotes: 1

Related Questions