Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make derived classes override ToString()?

(I'm working in .NET 4.0 beta, C#.)

I have an interface, and all classes derived from this interface should implement custom ToString() logic. Is that enforceable? If so, how?

like image 945
Domenic Avatar asked Aug 26 '09 02:08

Domenic


People also ask

Can we override toString method?

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.

Can we override toString () method in C#?

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.

What happens if you don't define toString () in your classes?

toString() method is not overrided in Class A. So, whenever you use reference variable of class A, it returns string containing className(along with package name), @ and followed by hexadecimal representation of memory address of object. There will not be enough information about state or properties of object.

Is toString always override?

So just because a data class defines a toString doesn't mean you shouldn't override it.


1 Answers

Not through an interface.

You'll need to use an abstract class for this.

-- Edit

You can just re-declare 'ToString' as abstract:

abstract class Foo
{
    public override abstract string ToString ();
}
like image 138
Noon Silk Avatar answered Sep 29 '22 15:09

Noon Silk