Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int32.Parse() VS Convert.ToInt32()?

Tags:

intID1 = Int32.Parse(myValue.ToString()); intID2 = Convert.ToInt32(myValue); 

Which one is better and why?

like image 431
Nano HE Avatar asked Sep 15 '10 00:09

Nano HE


People also ask

Which statement accurately describes the difference between Int32 TryParse () and convert ToInt32 ()?

Parse() and Int32. TryParse() can only convert strings. Convert. ToInt32() can take any class that implements IConvertible .

What is Int32 Parse?

Parse(String) Method is used to convert the string representation of a number to its 32-bit signed integer equivalent. Syntax: public static int Parse (string str); Here, str is a string that contains a number to convert.

Which conversion function of convert ToInt32 ()' and Int32 Parse ()' is efficient?

TOInt32() and Int32. Parse() is efficient? 1) Int32.

What is the difference between convert ToInt32 and convert toint64?

Thus int32 would be limited to a value between (-256^4/2) and (256^4/2-1). And int64 would be limited to a value between (-256^8/2) and (256^8/2-1).


2 Answers

They are exactly the same, except that Convert.ToInt32(null) returns 0.

Convert.ToInt32 is defined as follows:

    public static int ToInt32(String value) {         if (value == null)              return 0;         return Int32.Parse(value, CultureInfo.CurrentCulture);     } 
like image 115
SLaks Avatar answered Sep 28 '22 19:09

SLaks


Well, Reflector says...

public static int ToInt32(string value) {     if (value == null)     {         return 0;     }     return int.Parse(value, CultureInfo.CurrentCulture); }  public static int Parse(string s) {     return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } 

So they're basically the same except that Convert.ToInt32() does an added null check.

like image 20
Adam P Avatar answered Sep 28 '22 18:09

Adam P