Derek Rocco
Derek Rocco

Reputation: 11

Requiring Child Classes to call base.Foo() in overrides

I'm working on a Unity project which uses a good amount of inheritance. I have an abstract base class whose methods I want its children to always call (e.g. Awake).

I haven't worked with attributes much - is there a way to add an attribute to my ABC's Awake method which causes the child-class to log an error if they override Awake() without calling base.Awake() in its implementation?

Thanks!

Upvotes: 1

Views: 210

Answers (1)

tmaj
tmaj

Reputation: 34967

You could something like this:

public class A 
{
    public void Awake() 
    {
        Console.WriteLine("Everybody does X on awake");
        AwakeExtra();
    }

    public virtual void AwakeExtra() => Console.WriteLine("'A' also does A on awake");
}

public class B : A 
{
    public override void AwakeExtra() => Console.WriteLine("'B' also does B on awake");
}

Upvotes: 1

Related Questions