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?
Integer toString() in Java toString(int i) method returns a String object representing the specified integer.
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.
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.
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.
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