-1

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?

Rand Random
  • 7,300
  • 10
  • 40
  • 88
Yusif
  • 183
  • 2
  • 8
  • Neither the 2nd nor the 3rd are true. – Joel Coehoorn Apr 25 '23 at 15:26
  • 4
    The `is` operator exists in C#, you can verify your claims yourself. – gunr2171 Apr 25 '23 at 15:26
  • What you should be doing is [imposing generic constraints](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters) to ensure that this actually happens in your backend. Otherwise I have no idea what you are talking about here – Narish Apr 25 '23 at 15:35
  • 3
    did you test it? https://dotnetfiddle.net/mK3Dmh Notice: i have added an example for contravariant https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/in-generic-modifier – Rand Random Apr 25 '23 at 15:36
  • Intuition comes alongside experience. So its a personal things. – Ralf Apr 25 '23 at 15:37

1 Answers1

1

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.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132