views:

68

answers:

4

I was always curious.

Why does this work:

double Number = Convert.ToDouble(TextBox1.Text);

But this doesn't:

double Number = (double)TextBox1.Text;
+6  A: 

You can only cast if an explicit cast exists between the types. There is no explicit cast from string to double. Convert.ToDouble is not casting, it is parsing the string and attempting to convert it into a double. Note that it's not guaranteed to succeed, for example Convert.ToDouble("Hello there")

Matt Greer
+1  A: 

TextBox1.Text is a string type, that's a different type than double. Double isn't derived from string, and string isn't derived from double. Therefor they can't be casted.

For cases where conversions are possible, there's an IConvertible interface, that allows objects of different types to be converted to/from each other.

Sander Rijken
+3  A: 

I think what you are asking is...

When I type this line of code into the IDE:

double Number = (double)TextBox1.Text;

Why can't the compiler turn it into this implicitly:

double Number = Convert.ToDouble(TextBox1.Text);

The issue here is that you are using an explicit cast. What you are literally saying to the compiler is...

Even though I declared this chunk of memory to be X, I want you to treat it like a Y. The compiler is smart enough to know if it can be done or not. Since the chunk of memory you are trying to convert is a System.String, the compiler knows that there is no possible way to treat it as if it were a System.Double.

The static Convert methods are programatically parsing a value out and creating a brand new value in memory of the desired type, not simply using the same bytes in memory as though there were something else.

Josh
A: 

I think it's mostly a design choice by the author of one of the classes. Generally speaking, you use casts when changing from the from-type to the to-type and around are conceptually extensions or restrictions. For example, you could see int and short as a restricted versions of double, and a long as an extension of a byte.

These conversions are conceptually trivial or canonical (although they can still fail, for example when casting decimal to int and the decimal is too large to fit). They also mirror to some extent the up- and down-casting along type hierarchies and to interfaces. (Which you cannot control in C#.)

When dealing with strings, for example, this is no longer obvious, and you're talking about a conversion from one domain (text) to an entirely separate domain (numbers, dates, etc.), where you're even taking the execution context into consideration (e.g., the current CultureInfo). This lends itself more to a more explicit Convert operation.

Ruben