Why this won't compile? Maybe FW5 can enable that...
static void Main(string[] args)
{
List<Foo> foos = new List<Goo>();
}
public class Foo
{
}
public class Goo : Foo
{
}
Stackover flow says my post is mostly code... But that was may question so I'm trying to pass the code text ratio validation.... Hope that is enough
Now it is saying I'm not describing the problem right.. Just read it again seems fine by me...
Because a list of Goo is not a list of Foo. If that worked, you could do (at compile-time):
foos.Add(new Foo());
which clearly can't work, because the list can only take Goo instances.
Variance does exist (depending on the framework version), but is limited a: to interfaces and delegates (not concrete types like lists), and b: to known-all-"in" or known-all-"out" scenarios.
For example, the following will compile on recent framework / compiler versions:
IEnumerable<Goo> goos = new List<Goo>();
IEnumerable<Foo> foos = goos;
In this scenario, it works fine because every Goo is known statically to be a Foo. Technically, this uses the out part of IEnumerable<out T> signature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With