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?
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.
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.
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.
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() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With