收录日期:2021/01/23 06:24:01 时间:2010-03-31 04:58:43 标签:c#

Is better to use the below statement

Convert.ToInt32("0" + stringValue)

If not then why?

I know that it is better to user int.TryParse() function, which is better, but what about the above statement.

Better than what?

Personally, I think that using Convert.ToInt32("0" + stringValue) is an anti-pattern.

It doesn't provide anything useful, since:

  • A positive integer will still result in the same value.
  • If you pass it a negative number, it will throw.
  • It doesn't add any extra error checking
  • It DOES create an extra string concatenation, which is not used for anything, reducing performance for no reason
  • It adds extra complexity for no reason.

Just use Convert.ToInt32(stringValue) directly, or int.TryParse if you don't want to have exception handling in place.

The only case when that would have any use is if the string variable is a null reference. Concatenating with a zero character is totally pointless, though. As we are only after the null check performed by the string concatenation, a better version would concatenate with an empty string instead, as that doesn't break for negative values:

Convert.ToInt32(String.Empty + stringValue)

A better solution as it doesn't do a string concatenation:

Convert.ToInt32(stringValue ?? String.Empty)

An even better solution would be to check for the null value first, so that you don't have to parse the known string:

stringValue == null ? 0 : Convert.ToInt32(stringValue)