Francois Taljaard
Francois Taljaard

Reputation: 1477

C# call method before override method

Good day, I have a base class with a virtual method that needs to be overridden per implementation, but I would like to call the base method first before overriding. Is there a way to accomplish this without having to actually call the method.

public class Base
{
    public virtual void Method()
    {
        //doing some stuff here 
    }
}

public class Parent : Base
{
    public override void Method()
    {
        base.Method() //need to be called ALWAYS
        //then I do my thing 
    } 
}

I cannot always rely that the base.Method() will be called in the override, so I would like to enforce it somehow. This might be a design pattern of some kind, any approach to accomplish the result will do.

Upvotes: 3

Views: 2280

Answers (2)

Elias Navarro
Elias Navarro

Reputation: 97

You can use the decorator design pattern, applying this pattern you can attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality:

public abstract class Component
{
    public abstract void Operation();
}

public class ConcreteComponent1 : Component
{
    public override void Operation()
    {
        //logic
    }
}

public abstract class ComponentDecorator : Component
{
    protected readonly Component Component;

    protected ComponentDecorator(Component component)
    {
        Component = component;
    }

    public override void Operation()
    {
        if(Component != null)
            Component.Operation();
    }
}

public class ConcreteDecorator : ComponentDecorator
{
    public ConcreteDecorator(Component component) : base(component)
    {
    }

    public override void Operation()
    {
        base.Operation();
        Console.WriteLine("Extend functionality");
    }
}

Hope this helps!

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234665

One way is to define a public method in the base class, which calls another method that can be (or must be) overridden:

public class Base
{
     public void Method()
     {
        // Do some preparatory stuff here, then call a method that might be overridden
        MethodImpl()
     }

     protected virtual void MethodImpl() // Not accessible apart from child classes
     {      
     }
}

public class Parent : Base
{
    protected override void MethodImpl()
    {
       // ToDo - implement to taste
    } 
}

Upvotes: 3

Related Questions