Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is-a relationships in Generics

Suppose we have generic classes G1<T> and G2<T>: G1<T>. And classes C1 and C2: C1.

Of the following which is not true?:

G2<C1> is-a G1<C1>,
G1<C2> is-a G1<C1>,
G2<C2> is-a G1<C1>

Aside from these is there any case that would surprise intuition?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It is easy to check:

Console.WriteLine(new G2<C1>() is G1<C1>); // True
Console.WriteLine(new G1<C2>() is G1<C1>); // False
Console.WriteLine(new G2<C2>() is G1<C1>); // False

class C1{}
class C2:C1{}
class G1<T>{}
class G2<T>:G1<T>{}

Demo

The last two in general case are quite easy to explain. Imagine G1 being:

class G1<T>
{
    public T Data { get; set; }
}

Then if new G1<C2>() is G1<C1> would be true then the next would be possible –
((G1<C1>)new G1<C2>()).Data = new C1(); which obviously breaks type safety.

Something can be done with variance support in generic interfaces, but it is limited to interfaces.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading