Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c#: tryparse vs convert

Tags:

c#

parsing

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 Convert.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?

like image 471
Hemant Kothiyal Avatar asked May 22 '26 04:05

Hemant Kothiyal


1 Answers

If you know the value can be converted, 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.

like image 109
Matthew Scharley Avatar answered May 24 '26 18:05

Matthew Scharley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!