Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance in C# and call to base.X() using overriden function Y()

Tags:

c#

inheritance

I need to know something about inheritence 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) which derived from BaseClass. The problem is that somehow I want to override Y() function in ChildClass, and when the base.X() function is called, I want X() function to use overridden Y() function in ChildClass.

Someone suggested me to use 'delegate' keyword for Y function when overriding. But, I am not quite sure that this is gonna work.

Is this possible? Any suggestions?

like image 254
Ahmet Keskin Avatar asked Dec 01 '22 07:12

Ahmet Keskin


1 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 implementation of Y() in the ChildClass you can do this:

class ChildClass : BaseClass
{
    public override void Y()
    {
        // Some code here
        base.Y();
    }
}
like image 62
Garry Shutler Avatar answered Dec 06 '22 09:12

Garry Shutler