Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics inheritance... doesn't work [duplicate]

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...

like image 337
Amir Katz Avatar asked Jan 22 '26 09:01

Amir Katz


1 Answers

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.

like image 189
Marc Gravell Avatar answered Jan 23 '26 23:01

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!