UNeverNo
UNeverNo

Reputation: 583

Empty String to Double using (Try)Parse

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:

Upvotes: 5

Views: 18081

Answers (7)

Jens
Jens

Reputation: 3412

Out parameters has to be set, therefore if TryParse fails it will initialize the output to it's default before it returns, however you will and in the "else" loop... Meaning it failed...

Try running the code below, that will show you that TryParse actually overwrites the value, yet indicates that the parse fails...

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                ParseAndOutput("");
                ParseAndOutput("1.0");
                ParseAndOutput("ABC");
            }

            private static void ParseAndOutput(string input)
            {
                double value = -1;
                if (double.TryParse(input, out value))
                {
                    Console.WriteLine("Parse succeeded for '"+input+"', try parse changed to: " + value);
                }
                else
                {
                    Console.WriteLine("Parse failed for '" + input + "', try parse changed to:  " + value);
                }
            }
        }
    }

So both Parse and TryParse fails on string.Empty, they just report that failure differently which is the whole point of TryParse, it is never meant to throw an exception...

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838226

Why is giving me Parse an error and TryParse my expected value?

Because that's the way the interface is designed. TryParse does not throw an exception if the input has an invalid format. Instead it returns false.

Is there any way to get the error message out of TryParse (time is not the problem)?

No, but you can make your own error message.

if (double.TryParse(myString, out myValue))
{
    //do something
}
else
{
    throw new FooException("Problem!");
}

But if you want to throw an exception when there is an error it's simpler to just use Parse.

Upvotes: 1

keyboardP
keyboardP

Reputation: 69372

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.

Upvotes: 8

codingbiz
codingbiz

Reputation: 26386

TryParse allows you to convert without throwing exception and returns true if successful. The action you take depends on you

if (!double.TryParse(myString, out myValue))
{
//throw exception here
}

It is useful when you are not sure if input will always be numbers

Upvotes: 2

Humberto
Humberto

Reputation: 7199

Forget double.TryParse, as it won't tell you (by design) why the parsing failed. Do it The Old Way:

string myString = String.Empty;
double myValue = 0.0;

try
{
    myValue = double.Parse(myString);
}
catch (FormatException)
{
    // Now you have a meaningful story here!
}

Upvotes: 0

Carsten
Carsten

Reputation: 11606

TryParse is implemented somehow like this:

try
{
    Parse(...);
    return true;
}
catch
{
    return false;
}

So you can do it just the same way:

try
{
    double.Parse(str, out dbl);
}
catch (Exception ex)
{
    // Do something with ex.Message
    dbl = 0.0;
}

// Continue with dbl.

Upvotes: 0

Toni Petrina
Toni Petrina

Reputation: 7122

No, it is not possible to get the exact error message. You only want to know if it is possible to convert to double and the result, if it is possible. The exact reason why the conversion fails is hidden from you.

Upvotes: 2

Related Questions