Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the compiler allow Convert.ToString() to be assigned to an integer?

Tags:

c#

.net

I accidentally stumbled across something similar to the following in my code, it compiles fine but then obviously bombs at runtime:

dynamic fiftySixDynamic = 56;
int fiftySixInt = System.Convert.ToString(fiftySixDynamic);

Every overload of Convert.ToString() returns a string, so surely this shouldn't compile? What's going on here?

like image 582
JMK Avatar asked Apr 15 '16 20:04

JMK


People also ask

What is the use of integer ToString () in Java?

Integer toString() in Java toString(int i) method returns a String object representing the specified integer.

Can you use ToString on an int?

toString(int a) is an inbuilt method in Java which is used to return a String object, representing the specified integer in the parameter. Parameters: The method accepts one parameter a of integer type and refers to the integer needed to be converted to string.

What is the difference between convert ToString () and ToString () method?

ToString method displays a blank line but output using ToString method throws an un-handled exception. Convert. ToString handles null while ToString doesn't and throws a NULL reference exception.


1 Answers

You're using dynamic for the input to Convert.ToString. Because an input is dynamic, the method binding and type checking is deferred to run-time, so the compiler doesn't see that the only possible return type is string. The compiler basically stops all binding and type-checking at that point.

Even if you called fiftySixInt = fiftySixDynamic.ToString(), which can't have an overload that returns an int, you would not get any warning from the compiler.

One way to avoid compile-time bugs yet still allow for dynamic behavior is to cast the return:

int fiftySixInt = (string)System.Convert.ToString(fiftySixDynamic);

It looks redundant, but it tells the compiler to treat the return value as a string for binding purposes. The method is still bound at run-time, so if the return type is not a string, you'd get a run-time exception, but downstream methods would get bound at compile-time.

like image 122
D Stanley Avatar answered Oct 16 '22 01:10

D Stanley