开发者

what is the difference between Convert.ToInt16 or 32 or 64 and Int.Parse? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Whats the main difference between int.Parse() and Convert.ToInt32

Hi

I want to know what is the different between :

Convert.ToInt16 or Convert.ToInt32 or Convert.ToInt64

vs

Int.Pa开发者_运维技巧rse

both of them are doing the same thing so just want to know what the different?


Convert.ToInt converts an object to an integer and returns 0 if the value was null.

int x = Convert.ToInt32("43"); // x = 43;
int x = Convert.ToInt32(null); // x = 0;
int x = Convert.ToInt32("abc"); // throws FormatException

Parse convert a string to an integer and throws an exception if the value wasn't able to convert

int x = int.Parse("43"); // x = 43;
int x = int.Parse(null); // x throws an ArgumentNullException
int x = int.Parse("abc"); // throws an FormatException


Convert.ToInt32 will return 0 if the input string is null. Int32.Parse will throw an exception.


  1. Convert.To(s) doesn't throw an exception when argument is null, but Parse() does.Convert.To(s) returns 0 when argument is null.

  2. Int.Parse() and Int.TryParse() can only convert strings. Convert.To(s) can take any class that implements IConvertible.Hence, Convert.To(s) is probably a wee bit slower than Int.Parse() because it has to ask its argument what it's type is.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜