tags:

views:

175

answers:

3
+4  Q: 

Inheritence in C#

Hi all, 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?

+17  A: 
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();
    }
}
Garry Shutler
A: 

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

DanDan
There's no need to use the template pattern - just make Y virtual...
Jon Skeet
Yes, you can use virtual or abstract. The principle still holds.
DanDan