开发者

Is it better to use "0" concatenation in Convert.ToInt32() function call

Is better to us开发者_JS百科e 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜