(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?
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.
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.
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.
So just because a data class defines a toString doesn't mean you shouldn't override it.
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 ();
}
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