Inheriting in C # and calling base.X () using the override function Y ()

I need to know something about inheritance in C #. I have a class shown below:

Class BaseClass { public void X() { //Some code here Y(); } public void Y() { //Some code here } } 

Now I want to create another class (ChildClass) that was derived from BaseClass. The problem is that somehow I want to override the Y () function in ChildClass, and when the base.X () function is called, I want the X () function to use the overridden Y () function in ChildClass.

Someone suggested I use the "delegate" keyword for the Y function when overriding. But I'm not quite sure if this will work.

Is it possible? Any suggestions?

+4
source share
2 answers
 class BaseClass { public void X() { // Some code here Y(); } public virtual void Y() { // Some code here } } class ChildClass : BaseClass { public override void Y() { // Some code here } } 

If at some point you want to call the BaseClass Y() implementation in ChildClass , you can do this:

 class ChildClass : BaseClass { public override void Y() { // Some code here base.Y(); } } 
+19
source

It is possible. It is known as template . Declare your Y () function in the base class, but mark it as abstract. In a derived class, override this function. Calling X () will call the correct function.

0
source

All Articles