Force base method call

Viewed 22750

Is there a construct in Java or C# that forces inheriting classes to call the base implementation? You can call super() or base() but is it possible to have it throw a compile-time error if it isn't called? That would be very convenient..

--edit--

I am mainly curious about overriding methods.

14 Answers

I use the following technique. Notice that the Hello() method is protected, so it can't be called from outside...

public abstract class Animal
{
    protected abstract void Hello();

    public void SayHello()
    {
        //Do some mandatory thing
        Console.WriteLine("something mandatory");

        Hello();

        Console.WriteLine();
    }
}

public class Dog : Animal
{
    protected override void Hello()
    {
        Console.WriteLine("woof");
    }
}

public class Cat : Animal
{
    protected override void Hello()
    {
        Console.WriteLine("meow");
    }
}

Example usage:

static void Main(string[] args)
{
    var animals = new List<Animal>()
    {
        new Cat(),
        new Dog(),
        new Dog(),
        new Dog()
    };

    animals.ForEach(animal => animal.SayHello());
    Console.ReadKey();
}

Which produces:

enter image description here

Don't force a base call. Make the parent method do what you want, while calling an overridable (eg: abstract) protected method in its body.

Related