Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the main difference between int.Parse() and Convert.ToInt32

Tags:

c#

  • What is the main difference between int.Parse() and Convert.ToInt32()?
  • Which one is to be preferred
like image 328
jbcedge Avatar asked Oct 13 '08 23:10

jbcedge


People also ask

What is the difference between convert ToInt32 and int Parse?

Convert. ToInt32 allows null value, it doesn't throw any errors Int. parse does not allow null value, and it throws an ArgumentNullException error.

What is the difference between int Parse and int TryParse methods?

The difference in both methods is in the way they react when the string you are trying to convert to integer can't be converted to an integer. And in such a circumstance, the int. Parse() method will throw an exception whereas the int. TryParse() will return a boolean value of false.

What does convert ToInt32 mean?

ToInt32(String, Int32) Converts the string representation of a number in a specified base to an equivalent 32-bit signed integer. ToInt32(UInt64) Converts the value of the specified 64-bit unsigned integer to an equivalent 32-bit signed integer.

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


1 Answers

  • If you've got a string, and you expect it to always be an integer (say, if some web service is handing you an integer in string format), you'd use Int32.Parse().

  • If you're collecting input from a user, you'd generally use Int32.TryParse(), since it allows you more fine-grained control over the situation when the user enters invalid input.

  • Convert.ToInt32() takes an object as its argument. (See Chris S's answer for how it works)

    Convert.ToInt32() also does not throw ArgumentNullException when its argument is null the way Int32.Parse() does. That also means that Convert.ToInt32() is probably a wee bit slower than Int32.Parse(), though in practice, unless you're doing a very large number of iterations in a loop, you'll never notice it.

like image 181
Dave Markle Avatar answered Oct 11 '22 13:10

Dave Markle