Is this scenario possible in C # method inheritance

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

Suppose 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 introduce a base parameter each time in a child class method. So is this possible?

+4
source share
2 answers

This function is called covariance of formal parameters. It is not supported by C #. Also, it is not typical.

Two variations on it are typical. Covariance of formal parameters and covariance of the return type. C # supports those for general delegate conversions, and for group methods delegate conversions, but does not support them for overriding virtual methods.

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

+6
source

No. Parameters must be accurate.

The whole purpose of virtual / overriding is that you usually call a method from a base class reference:

  Base b = ....; b.SomeMethod(x); // might actually call ChildA.SomeMethod() or ChildB.SomeMethod() 
+3
source

Source: https://habr.com/ru/post/1484744/


All Articles