adminSoftDK
adminSoftDK

Reputation: 2092

Is it possible to skip overriden methods code when based on base code

Ive got quick c# question. If I have method like this

    protected virtual void Delete(Guid? guidId)
    {
    }

Then I override it like this

    protected override void Delete(Guid? id)
    {
        if (id != null)
        {
          code goes here 
        }
    }

I could place that if statement inside the base method like this

    protected virtual void Delete(Guid? guidId)
    { 
        if (id != null)
        {
          code goes here 
        }
    }

And then call it like this

    protected override void Delete(Guid? id)
    {
      base.Delete(id);
      code goes here  
    }

But now in the overridden method, I don’t want to carry on if the base method did not go inside that if statement. I was just wondering if this was possible. Thank you :)

Upvotes: 0

Views: 293

Answers (2)

dcastro
dcastro

Reputation: 68720

It seems like you're looking for the Template Method pattern, also often known as hook methods.

public class Base 
{
    protected void Delete(Guid? id)
    { 
        if (id != null)
        {
           //code goes here

           //execute hook only if id is not null
           OnDelete(id);
        }
    }

    protected virtual void OnDelete(Guid? guid) {}
}


public class Derived : Base
{
    protected override void OnDelete(Guid? guid)
    {
        //code goes here
    }
}

If you want to force all base classes to implement the hook, make the method abstract. Otherwise, if implementing the hook is optional, define it as an empty method, as I've done above.

This pattern employs a very powerful principle: the Hollywood principle. Don't call us, we'll call you! The derived class doesn't call the base class, as in your example - instead, the base class will call the derived class if appropriate.

Upvotes: 2

Matthew Watson
Matthew Watson

Reputation: 109762

Change the method to return a bool to indicate if the branch was taken, e.g.:

class Base
{
    protected virtual bool Delete(Guid? id)
    {
        bool result = false;

        if (id != null)
        {
            // ...

            result = true;
        }

        return result;
    }
}

internal class Derived : Base
{
    protected override bool Delete(Guid? id)
    {
        if (!base.Delete(id))
            return false;

        // ...

        return true;
    }
}

Upvotes: 2

Related Questions