tags:

views:

445

answers:

2

Today I read an article where it's written that we should always use TryParse(string, out MMM ) for conversion rather than Convert.ToMMM().

I agree with article but after that I got stuck in one scenario?

When there will always be some valid value for the string and hence we can also use Convert.ToMMM() because we don't get any exception from Covert.ToMMM().

What I would like to know here is: is there any performance impact when we use TryParse because when I know that the out parameter is always going to be valid then we can use Convert.ToMMM() rather TryParse(string, out MMM)

What do you think?

+5  A: 

If you know the value can be coverted, just use Parse(). If you 'know' that it can be converted, and it can't, then an exception being thrown is a good thing.

EDIT: Note, this is in comparison to using TryParse or Convert without error checking. If you use either of the other methods with proper error checking then the point is moot. I'm just worried about your assumption that you know the value can be converted. If you want to skip the error checking, use Parse and die immediately on failure rather than possibly continuing and corrupting data.

Matthew Scharley
+1  A: 

When the input to TryParse/Convert.ToXXX comes from user input, I'd always use TryParse. In case of database values, I'd check why you get strings from the database (maybe bad design?). If string values can be entered in the database columns, I'd also use TryParse as you can never be sure that nobody modifies data manually.

EDIT
Reading Matthew's reply: If you are unsure and would wrap the conversion in a try-catch-block anyway, you might consider using TryParse as it is said to be way faster than doing a try-catch in that case.

Thorsten Dittmar