Why can't you impose a restricted open generic type typed for a restricted type?

I think I am missing something, why I can not compile this:

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

abstract class Bar
{ }

class MyBar : Bar
{ }

static void Main(string[] args)
{
    var fooMyBar = new Foo<MyBar>();
    AddMoreFoos(fooMyBar);
}

static void AddMoreFoos<T>(Foo<T> FooToAdd) where T : Bar
{
    var listOfFoos = new List<Foo<Bar>>();
    listOfFoos.Add(FooToAdd); //Doesn't compile
    listOfFoos.Add((Foo<Bar>)FooToAdd); //doesn't compile
}
+5
source share
2 answers

You make things a little more confusing than they should be using the list here ... the easiest way to see the effect is this:

// This won't compile
Foo<Bar> fooBar = new Foo<MyBar>();

Given that this does not compile, it is not surprising that you cannot add Foo<MyBar>toList<Foo<Bar>>

So why not Foo<MyBar>a Foo<Bar>? Since general classes are not covariant.

General variance was introduced only in C # 4, and it only works for interfaces and delegates. This way you can (in C # 4):

IEnumerable<MyBar> x = new List<MyBar>();
IEnumerable<Bar> y = x;

but you could not:

IList<MyBar> x = new List<MyBar>();
IList<Bar> y = x;

, - NDC 2010 - "".

+9

, , Foo<int>, : .

var listOfFoos = new List<Foo<T>>(), Add .

(EDIT: , , Foo<T> - , T Bar).

+3

All Articles