Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to disable implicit ToString() call?

Tags:

c#

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.

like image 667
avs099 Avatar asked Mar 11 '13 18:03

avs099


People also ask

Is toString implicitly called?

Note : toString() method is implicitly called when any object of a class is printed.

Can we override toString method in JavaScript?

toString() ). This method is inherited by every object descended from Object , but can be overridden by descendant objects (for example, Number. prototype. toString() ).

What will happen if you will not override toString method?

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.

Why is toString automatically called?

toString is automatically called for the frog1 Object constructed by the default constructor.


1 Answers

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)

like image 55
JaredPar Avatar answered Oct 19 '22 08:10

JaredPar