You can't cast a string to a double, even if the string contains a value like "1234.56". Casting is only allowed when the class of the object being casted and the "destination" class are related, or when an explicit cast operator for that specific pair of classes has been created (which creates a new object of the destination class with the info from the source - changes to the destination are not reflected back in the source).
For example, you can cast from an
int
to a
double
and vice versa, or from a
Form
to a
Control
because the former derives from the latter - but you may get an error trying to cast in the other direction as the
Button
class for example is not directly related to a
Form
What you have to do is convert the data using the
double.TryParse method[
^]:
string str = "123.45";
double d;
if (!double.TryParse(str, out d))
{
... report problem or log it ...
return;
}
Console.WriteLine(d);
You could use the
double.Parse method[
^] but if the source is not a valid double value then an exception will be thrown, potentially crashing your app.