How to force the derived class to override a method that returns its class name only?

Viewed 36

I don't know what pattern I have to implement for forcing the derived class to override the method Print returning only its class name.

class Base
{
    protected virtual string Print() => nameof(Base);

    static void Main(string[] args)
    {
        Base b = new Derived();
        Console.WriteLine(b.Print());
    }
}

class Derived : Base
{
    protected override string Print() => nameof(Derived);
}
2 Answers

You can enforce what you need by implementing generic logic in the base class:

protected string Print() => this.GetType().Name;

That way, if you call the method from Base, you will always get derived class name.

You could use some generics and type constraint on the base class. Not sure what you are trying to accomplish.

    private static void Main(string[] args)
    {
        var instance = new Derived();
        Console.WriteLine(instance.Print());
        Console.ReadLine();
    }

    public abstract class Base<TChild>
        where TChild : Base<TChild>
    {
        public string Print() => typeof(TChild).Name;
    }

    public class Derived : Base<Derived>
    {
    }
Related