Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force subclasses of an interface to implement ToString

Tags:

c#

oop

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?

like image 502
rjohnston Avatar asked Feb 04 '09 07:02

rjohnston


People also ask

Can we override toString method in interface?

We can override the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form.

Do interfaces have a toString method?

toString is declared inside Object . When an Object implements an interface it must have a toString method. Therefore any object reference, be it an interface or an enum must have all the object methods: clone.

Why should you override the toString () method?

When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code. For information about how to use format strings and other types of custom formatting with the ToString method, see Formatting Types.


2 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();  } 
like image 60
Jon Skeet Avatar answered Oct 24 '22 10:10

Jon Skeet


abstract class Foo {     public override abstract string ToString(); }  class Bar : Foo {     // need to override ToString() } 
like image 27
Andrew Peters Avatar answered Oct 24 '22 09:10

Andrew Peters