Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this scenario possible in c# method inheritance

Tags:

c#

inheritance

I want to know if this scenario is possible in C# inheritance.

Let's assume we have 3 classes.

public class Base
{   
    public abstract void SomeMethod(Base param);
}

public class ChildA : Base
{   
    public override void SomeMethod(ChildA param);
}

public class ChildB : Base
{   
    public override void SomeMethod(ChildB param);
}

I do not want to typecast the base param everytime in the child class method. So, is this possible?

like image 355
Jonna Avatar asked Dec 27 '22 02:12

Jonna


1 Answers

That feature is called formal parameter type covariance. It is not supported by c#. Also it is not typesafe.

Two variations on it are typesafe. Formal parameter contravariance and return type covariance. C# does support those for generic delegate conversions and for method group to delegate conversions but does not support them for virtual method overriding.

You're out of luck here I'm afraid.

like image 57
Eric Lippert Avatar answered Jan 12 '23 05:01

Eric Lippert