TryParse?

  • Thread starter Thread starter DoB
  • Start date Start date
D

DoB

Hi,

As far, as I know, this is not a good code:
------------------------------------------
double d = 0;
try
{
d = double.Parse(str);
}
catch { }
------------------------------------------

What is the recommended substitution? Using TryParse?

Regards,
DoB
 
DoB said:
Hi,

As far, as I know, this is not a good code:
------------------------------------------
double d = 0;
try
{
d = double.Parse(str);
}
catch { }
------------------------------------------

What is the recommended substitution? Using TryParse?

Regards,
DoB

Indeed,

double d = 0;
if(!Double.TryParse(str, out d))
{
// Error handling
}
 
Hi,

As far, as I know, this is not a good code:
------------------------------------------
double d = 0;
try
{
d = double.Parse(str);}

catch { }
------------------------------------------

What is the recommended substitution? Using TryParse?

Regards,
DoB

Yes:

public static void Main()
{
string str = "not_a_double";
double d = double.NaN;
if (!double.TryParse(str, out d))
{
// d is now 0.0, handle failure case
}
}

John
 
TryParse is the preferred method. As Morten has stated, you should handle
cases where you cannot parse out a number from the string input.

One more note: Your code is not necesarily bad, provided you can always
guarantee a number is going in. If it is all your code, and all internally
dependent (ie, there is no external user input that can influence the
string), you might get away with it.

The other option is to test if the string is a number, but since TryParse
does this for you, that would cost extra cycles, except perhaps at the byte
level :-)

--
Gregory A. Beamer
MVP, MCP: +I, SE, SD, DBA

Subscribe to my blog
http://gregorybeamer.spaces.live.com/lists/feed.rss

*************************************************
| Think outside the box!
|
*************************************************
 
John Duval said:
Yes:

public static void Main()
{
string str = "not_a_double";
double d = double.NaN;

There is no need to set a value before calling TryParse, it is an out param
so the prior value isn't used.
 
There is no need to set a value before calling TryParse, it is an out param
so the prior value isn't used.

Right, I was highlighting the fact that TryParse will change the value
to 0 if the parsing fails.
 
Back
Top