Force subclasses of an interface to implement ToString

Viewed 26027

Say I have an interface IFoo and I want all subclasses of IFoo to override Object's ToString method. Is this possible?

Simply adding the method signature to IFoo as such doesn't work:

interface IFoo
{
    String ToString();
}

since all the subclasses extend Object and provide an implementation that way, so the compiler doesn't complain about it. Any suggestions?

7 Answers

I don't believe you can do it with an interface. You can use an abstract base class though:

public abstract class Base
{
    public abstract override string ToString(); 
}
abstract class Foo
{
    public override abstract string ToString();
}

class Bar : Foo
{
    // need to override ToString()
}

Jon & Andrew: That abstract trick is really useful; I had no idea you could end the chain by declaring it as abstract. Cheers :)

In the past when I've required that ToString() be overriden in derived classes, I've always used a pattern like the following:

public abstract class BaseClass
{
    public abstract string ToStringImpl();

    public override string ToString()
    {
        return ToStringImpl();
    }    
}

Sorry to bury out this old thread from the grave, specially as our dear @jon-skeet already provided his own answer.

But if you want to keep the interface and not use an abstract class, I guess this is still possible by simply having your interface implementing the System.IFormattable interface.

interface IFoo : IFormattable
{
}

The only thing to keep in mind is, to properly implement this IFormattable, the concrete implementation should overwrite the Object.ToString() as well.

This is clearly explained in this nice post.

Your concrete class is now like

public class Bar : IFoo
{
    public string ToString(string format, IFormatProvider formatProvider)
    {
        return $"{nameof(Bar)}";
    }

    public override string ToString()
    {
        return ToString(null, System.Globalization.CultureInfo.CurrentCulture);
    }
}

Hope this might still help anyone.

Implementing an interface method implicitly seals the method (as well as overriding it). So, unless you tell it otherwise, the first implementation of an interface ends the override chain in C#.

Essential .NET

Abstract class = your friend

Check this question

I don't think you can force any sub-class to override any of the base-class's virtual methods unless those methods are abstract.

Related