I would like to automatically call a base class method for a class that inherits from the base class.

From the extent of my limited knowledge, I know I can do this using base.Method().

public abstract class Foo
    {
        private int a;
        private float b;

        public virtual void Init()
        {
            a = 1;
            b = 2.5f;
        }
    }

    public class Bar : Foo
    {
        public float c;

        public Bar() { }

        public override void Init()
        {
            base.Init();

            c = 3.0f;
        }
    }

Is there any way I can automatically call the base Init method and the overriding method using just one call?

So if I were to override the base Init method in a derived class, then base.Init() would not need to be explicitly typed as it would be called automatically, along with the override Init method?

Edited 6 Years Ago by DaveTran: n/a

You can call a protected overridded method from the base class.
See below:

public abstract class Foo
{
    private int a;
    private float b;

    protected abstract void DoInit();

    public void Init()
    {
        a = 1;
        b = 2.5f;
        this.DoInit();
    }
}

public class Bar : Foo
{
    public float c;

    public Bar() { }

    protected override void DoInit()
    {
        c = 3.0f;
    }
}

public class FooBar
{
    public void Func()
    {
        Bar bar = new Bar();
        bar.Init(); //<-- calling Init executes Foo.Init and Bar.DoInit
    }
}

Edited 6 Years Ago by nick.crane: n/a

Comments
Great!

That is the design I'm after, thank you very much.

The one downside I can see is that you can still access Init from the derived class through base.Init().

Preventing a derived class from having access to public base class functions would be like having a TV with built in DVD and the TV not allowed to execute DVD.Play().

This question has already been answered. Start a new discussion instead.