Empty String to Double using (Try)Parse

UNeverNo picture UNeverNo · Dec 19, 2012 · Viewed 13.4k times · Source

I've got a with 1.1 build system here using Parse for converting values (now it's 3.5).

string myString = String.Empty;
double myValue = double.Parse(myString);

throws a FormatException (I expected 0.0).

If I rewrite that using 2.0+

string myString = String.Empty;
double myValue;
if (double.TryParse(myString, out myValue))
    //do something

I get the wanted 0.0, but unfortunately I lose the possibility to get a meaningful error message (in the else tree).

Why is giving me Parse an error and TryParse my expected value? Is there any way to get the error message out of TryParse (time is not the problem)?

I don't want to work around it like that:

  • Avoid the error using if...then

    myValue = myString.Length == 0 ? 0.0 : double.Parse(myString);
    
  • Two Calls if an error occured

    if (!double.TryParse(myString, out myValue))
        myValue = double.Parse(myString);
    

Answer

keyboardP picture keyboardP · Dec 19, 2012

Parse throws an exception if the string cannot be be parsed and TryParse returns a bool. You can handle this bool (true if the parsing was successful, else false) to display the success/error message you want to show.

Since myValue is an out parameter it has to be set by the method so, if the string cannot be parsed, TryParse sets it as 0.0 which is why you're getting that number when using the TryParse method.