C #: tryparse vs convert

I read an article today that says that we should always use TryParse (string, out MMM) for conversion, not Convert.ToMMM ().

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

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

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

What do you think?

+2


source to share


3 answers


If you know the value can be closed, just use Parse()

. If you "know" that it can be converted, and it cannot, then the exception thrown is good.



EDIT: Please note that this is versus using TryParse

or Convert

without error checking. When using any of the other methods, with actual error checking, the point is moot. I'm just worried about your assumption that you know the value can be converted. If you want to skip error checking, use Parse and die immediately on failure rather than continuing and corrupting data.

+9


source


When input to TryParse

/ Convert.ToXXX

comes from user input, I will always use TryParse

. In the case of database values, I would check why you are getting string

from the database (bad design maybe?). If string values ​​can be entered in the database columns, I would also use it TryParse

, since you can never be sure that nobody is manually modifying the data.



EDIT
Reading Matthew's answer: if you are unsure and still converting to a try-catch block, you can use TryParse

as it is said to be faster than trying try-catch in this case.

+1


source


There is a significant difference in the development approach you take.

Convert . Converting "primitive" data to another type and appropriate format using multiple parameters
Case and point - converting an integer number to its bitwise representation... Or a hexadecimal number (as a string) to an integer, etc.

Error messages . Conversion error message - for problems in multiple cases and at multiple stages of the conversion process.

TryParse: Transfer without transfer from one data format to another. Enable T / F control from possible or not.
Error messages: NONE
NB: Even after transferring data to a variable - the data is transferred by default of the type that we are trying to parse.

Parsing : essentially taking some data in one format and transferring it to another. No performances and nothing out of the ordinary. Error Messages: Format Oriented

PS Correct me if I missed something or didn't explain it well enough.

0


source







All Articles