JMK
JMK

Reputation: 28059

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

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?

Upvotes: 14

Views: 1356

Answers (1)

D Stanley
D Stanley

Reputation: 152576

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.

Upvotes: 36

Related Questions