9

Challenge: Please create an instance of the following class (using any type as T):

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

You may use any technique you like; plain "new MyClass...", using reflection, hacking MSIL, whatever.

Mattias Larsson
  • 763
  • 6
  • 15
  • 1
    Giving insight on what you want to achieve may help people give better alternative answers. – J.N. Mar 12 '12 at 07:31
  • 1
    possible duplicate of [Recursive generic types](http://stackoverflow.com/questions/647533/recursive-generic-types) – Amber Mar 12 '12 at 07:32
  • I really have no purpose of this weird construction. Frankly I didn't think it was possible, so it's cool that I got an answer. (And, no, it's not a homework question... ;-) – Mattias Larsson Mar 12 '12 at 08:45
  • I actually had a purpose for this. An interface that has a collection of itself, *e.g.* `interface IPerson where T : IPerson { IEnumerable Subordinates }`. Implementers of the interface will need Subordinates to be a collection of the concrete type `T`, otherwise they have all kinds of problems with co/contravariance of a generic collection. IEnumerable would make things difficult. – AaronLS Feb 04 '13 at 17:06

1 Answers1

12
static class Program {
    static void Main() {
        Foo<Bar> foo = new Foo<Bar>();
    }
}
class Foo<T> where T : Foo<T> {}
class Bar : Foo<Bar> {}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900