4

Possible Duplicate:
Why isn't there generic variance for classes in C# 4.0?

Example:

interface foo<out T> where T : BaseThing { }

compiles

class foo<out T> where T : BaseThing { }

does not.

Is this just unsupported, or is there some reason why it can never work or doesn't make logical sense?

Edit: Here's what I Wanted to do in case someone was wondering...

        class BaseThing { }
        class DerivedThing : BaseThing { }

        class foo<out T> where T : BaseThing { }
        class bar : foo<DerivedThing> { }

        private void test()
        {
            foo<BaseThing> fooInstance = new bar();
        }
Community
  • 1
  • 1
Erix
  • 7,059
  • 2
  • 35
  • 61
  • Well, the [documentation](http://msdn.microsoft.com/en-us/library/dd469487) says that `out` is only supported for interfaces and delegates. As for why it was designed that way, I am sure Eric Lippert will end up seeing this question and giving you a comprehensive answer (not enough use cases, or all use cases are not common etc...). – Oded Aug 10 '12 at 19:04

1 Answers1

3

The out modifier tells the compiler that the type parameter can be covariant. This means that use of types of T could be more-derived. Since you're using a specific class (e.g. a constructed generic type), there is only one instance of the concrete type so there is not a more-derived type in play. Multiple types can implement an interface like foo, which means you're dealing with potentially different types of T, in which case one of those T types may be more-derived.

Peter Ritchie
  • 35,463
  • 9
  • 80
  • 98