9

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.Parse

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

Community
  • 1
  • 1
Saleh
  • 2,657
  • 12
  • 46
  • 73
  • 3
    Dupe of http://stackoverflow.com/questions/199470/whats-the-main-difference-between-int-parse-and-convert-toint32 – stefan Mar 07 '11 at 22:06

3 Answers3

10

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
Homam
  • 23,263
  • 32
  • 111
  • 187
  • I tried these examples (using .NET 4 and .NET 3.5) and `Convert.ToInt32("abc");` will throw a `System.FormatException` just like `int.Parse("abc");` does. The only time that no exception is thrown is on `Convert.ToInt32(null);` – Joshua Rodgers Mar 08 '11 at 16:41
  • @Joshua Rodgers: Thanks a lot, I corrected my answer. – Homam Mar 09 '11 at 09:44
1

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

Joshua Rodgers
  • 5,317
  • 2
  • 31
  • 29
1
  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.

Vishal
  • 12,133
  • 17
  • 82
  • 128