petko_stankoski
petko_stankoski

Reputation: 10723

Avoiding try-catch by using tryparse instead of parse

In a lot of places in my code I have this:

try
{
    price = double.Parse(sPrice.Replace(",", "."), CultureInfo.InvariantCulture);
}
catch
{
    price  = 0;
}

I read somewhere that if the exception is thrown in the try block, it takes a lot of time being caught.

So, I'd like to use tryparse instead of parse, like this:

if (!double.TryParse(sPrice, out price))
{
     price  = 0;
}

Is this a good practice? Will it take less time?

Upvotes: 3

Views: 329

Answers (2)

Zdeslav Vojkovic
Zdeslav Vojkovic

Reputation: 14591

Yes, TryParse is faster.

However, this smells like a premature optimization to me, unless you expect Parse to be called in a tight loop with many invalid input strings.

You should choose not depending on speed but depending on requirements and what kind of data you expect to get. Also, consider another option: Convert.ToDouble

Upvotes: 3

Pawan Nogariya
Pawan Nogariya

Reputation: 8990

Two benefits I feel of using TryParse

  1. It is fast as compared to try.. catch...
  2. You will always have value in your variable, either the one you want to assign or the default one. So you can use your variable directly once it is passed to TryParse

Upvotes: 1

Related Questions