I'm wondering if there is a way to get a compilation error for this code:
var customer = new SomeCustomerClass();
Console.WriteLine("Customer address:" + customer);
so I will be forced to write something like this:
var customer = new SomeCustomerClass();
Console.WriteLine("Customer address:" + customer.FormatAddress());
Console.WriteLine("Customer accounts:" + customer.FormatAccounts());
If "ToString" would be an interface, I could do that using explicit interface implementation in my class.
Thanks.
Note : toString() method is implicitly called when any object of a class is printed.
toString() ). This method is inherited by every object descended from Object , but can be overridden by descendant objects (for example, Number. prototype. toString() ).
So, whenever you use or print a reference variable of type in which toString() method is not overrided, you will get an output like above. You will not get what the object actually has in it. There will be no information about state or properties of an object.
toString is automatically called for the frog1 Object constructed by the default constructor.
There is no way to prevent this code at compile time. Object.ToString
is a part of the public contract of every object and there are no ways to prevent it from being invoked at compile time. In this particular case the compiler will resolve the +
to String.Concat(object, object)
and the implementation ends up invoking Object.ToString
. There is no way to change this. I think your smoothest path forward is to override ToString
and have it call into FormatAddress
Please do not change ToString
to throw an exception as a few others are suggesting. The majority of .Net expects that ToString
exists and is non-throwing. Changing that will have many unexpected negative side effects to your program (including killing the debug experience for those objects)
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