Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Difference Between Convert.Int32() and Int32.Parse()?

Tags:

.net

I Have some confusion while using Convert.Int32() and int32.Parse(). When we use Convert.Int32() or int32.Parse()...

like image 824
Vijjendra Avatar asked Sep 30 '09 20:09

Vijjendra


People also ask

What is the difference between convert ToInt32 and int Parse?

In brief, int. Parse and Convert ToInt32 are two methods to convert a string to an integer. The main difference between int Parse and Convert ToInt32 in C# is that passing a null value to int Parse will throw an ArgumentNullException while passing a null value to Convert ToInt32 will give zero.

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


3 Answers

Convert.ToInt32() will attempt to convert anything - be it char, double, object, what have you - into an Int32. Int32.Parse() only works for strings.

EDIT: In response to OP's comment, I have a quote taken from this thread:

Basically the Convert class makes it easier to convert between all the base types.

The Convert.ToInt32(String, IFormatProvider) underneath calls the Int32.Parse. So the only difference is that if a null string is passed to Convert it returns 0, whereas Int32.Parse throws an ArgumentNullException.

It is really a matter of choice whichever you use.

like image 171
Matthew Jones Avatar answered Oct 11 '22 05:10

Matthew Jones


Expanding on Matthew's answer.

Convert.ToInt32 allows for user defined conversions in an extendable manner. For any non-predefined conversion (mostly primitives), The Convert class will check and see if the type implements IConventible and if so use it to allow the object to define it's own conversion to Int32 (and many other types).

like image 29
JaredPar Avatar answered Oct 11 '22 07:10

JaredPar


Convert.ToInt32 will convert null into 0; Int32.Parse will throw an exception if you pass it null. Also, as Matthew Jones said, Int32.Parse only works for strings.

See this article for more information

like image 41
Jacob Krall Avatar answered Oct 11 '22 05:10

Jacob Krall