Friday Quiz: Question on .NET 2.0 Generics

Published 20 August 04 09:26 AM | Scott Mitchell

Here's a little question that has me stumped, perhaps someone out there in the intraweb can answer this for me.

With Generics in 2.0 you can impose constraints on the type that can be specified by the developer. For example, I could create a class:

class Foo<T> where T : Bar
{
...
}

This would only allow developers to create a Foo instance where the type specified via the Generic was of type Bar, or derived from Bar. Ok, great. Now imagine that I have a class SuperFoo<U>, and I want U to be of type Foo<T>, or a class derived from Foo<T>. That is, I want to be able to say later:

SuperFoo<Foo<int>> blah;

How do I specify that? If I try:

class SuperFoo<S> where S : Foo

I get an error because Foo is not a type, Foo<T> is the type. If I try:

class SuperFoo<S> where S : Foo<X>

It barfs because X is an undefined type. Finally, if I try:

class SuperFoo<S> where S : Foo<S>

It compiles the class in this instance, but I can't create a type of this class. That is, if I do:

SuperFoo<Foo<int>> blah;

It says that Foo<int> isn't convertible to Foo<Foo<int>>, which seems to make sense since in the class definition, S is Foo<int>, so if S must be of type Foo<S> then it must be Foo<Foo<S>>.

So does anyone know how to define a class that uses generics to constrain the generic type so that the type is a generic type itself?

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Archives

My Books

  • Teach Yourself ASP.NET 4 in 24 Hours
  • Teach Yourself ASP.NET 3.5 in 24 Hours
  • Teach Yourself ASP.NET 2.0 in 24 Hours
  • ASP.NET Data Web Controls Kick Start
  • ASP.NET: Tips, Tutorials, and Code
  • Designing Active Server Pages
  • Teach Yourself Active Server Pages 3.0 in 21 Days

I am a Microsoft MVP for ASP.NET.

I am an ASPInsider.