Hemant Kothiyal
Hemant Kothiyal

Reputation: 4152

c#: tryparse vs convert

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?

Upvotes: 3

Views: 5983

Answers (3)

Vasil
Vasil

Reputation: 312

There is a significant difference regarding the developing approach you use.

Convert: Converting one "primitive" data into another type and corresponding format using multiple options
Case and point - converting an integer number into its bit-by-bit representation**. Or hexadecimal number (as string) into an integer, etc...
Error Messages: Conversion Specific Error Message - for problems in multiple cases and at multiple stages of the conversion process.

TryParse: Error-less transfer from one data format to another. Enabling T/F control if possible or not.
Error Messages: NONE
NB: Even after passing the data into a variable - the data passed is the default of the type we try to parse into.

Parse: in essence taking some data in one format and transferring it into another. No representations and nothing fancy.
Error Messages: Format-oriented

P.S. Correct me if I missed something or did not explain it well enough.

Upvotes: 1

Matthew Scharley
Matthew Scharley

Reputation: 132514

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.

Upvotes: 9

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56727

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.

Upvotes: 1

Related Questions