I was always curious.
Why does this work:
double Number = Convert.ToDouble(TextBox1.Text);
But this doesn’t:
double Number = (double)TextBox1.Text;
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I think what you are asking is…
When I type this line of code into the IDE:
Why can’t the compiler turn it into this implicitly:
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.