bleat interteiment
bleat interteiment

Reputation: 1459

Is there a way so that returning from the base virtual method would affect override too?

Here's a quick example of what I mean:

//Base class
public virtual void Equip(Item item) {
    if (item == null) return;
    SetItem(item);
}

//Interited class
public override void Equip(Item item) {
    base.Equip(item);
    //returning doesn't work. I have to rewrite all of my conditions or there's better approach?
    someList.Add(item);
}

So basically, my question is, when you call base virtual method, you're calling it like any other function and it doesn't affect the override method whatsoever? And there is no other way of returning from a function aside from rewriting all of my ifs?

Upvotes: 1

Views: 95

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239764

You can split the base class method in two, and only allow the overridden behaviour once validation is complete:

//Base class
public void Equip(Item item) {
    if (item == null) return;
    EquipOnceValidated(item);
}

protected virtual void EquipOnceValidated(Item item) {
    SetItem(item);
}

//Interited class
protected override void EquipOnceValidated(Item item) {
    //Decide if we still want to call the base class method or not
    someList.Add(item);
}

Upvotes: 1

Related Questions