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
Morten Wennevik [C# MVP] - 14 Mar 2008 12:14 GMT
> Hi,
>
[quoted text clipped - 12 lines]
> Regards,
> DoB
Indeed,
double d = 0;
if(!Double.TryParse(str, out d))
{
// Error handling
}

Signature
Happy Coding!
Morten Wennevik [C# MVP]
John Duval - 14 Mar 2008 12:19 GMT
> Hi,
>
[quoted text clipped - 12 lines]
> 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
Ben Voigt [C++ MVP] - 14 Mar 2008 18:26 GMT
>> Hi,
>>
[quoted text clipped - 19 lines]
> 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.
> if (!double.TryParse(str, out d))
> {
[quoted text clipped - 3 lines]
>
> John
John Duval - 14 Mar 2008 18:55 GMT
> >> Hi,
>
[quoted text clipped - 30 lines]
>
> > John
Right, I was highlighting the fact that TryParse will change the value
to 0 if the parsing fails.
Cowboy (Gregory A. Beamer) - 14 Mar 2008 17:12 GMT
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 :-)

Signature
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!
*************************************************
> Hi,
>
[quoted text clipped - 12 lines]
> Regards,
> DoB