C#C
C#3y ago
joren

❔ Covariance and Contravariance C#

So I stumbled on this topic and I dont seem to grasp it properly, though I saw the following example somewhere:

class Base
{
  void func() { ... }
}
class Derived : Base
{
  void fuc() { ... }
}

Base a = new Base(); // obv fine
Base b = new Derived(); // obv fine


Both now can call func(), but b cannot call fuc() too as its treated as a Base (reference) type. Now in C++, you'd just cast b to Derived and it'd work and be perfectly valid code. The sources I looked at, mentioned that this is why covariance/contravariance exists?
Was this page helpful?