I Have some confusion while using Convert.Int32() and int32.Parse(). When we use Convert.Int32() or int32.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.
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.
Parse() and Int32. TryParse() can only convert strings. Convert. ToInt32() can take any class that implements IConvertible .
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).
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With