Convert.ToInt32() and Int32.Parse()
Even though both looks different but do similar operations. I wish to know whether it is used for different purposes.
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Posted Dec 10, 2011, 9:24 AM
SenthilkumarPosted Dec 10, 2011, 8:19 AM
But the Convert.ToInt32() is a type safe conversion. why because you can't predict the value at the run time. in case value is null then it can be assumed as zero rather than throw the exception at the certain cases.
but the int32.parse do not have the control to implicitly convert null into zero value. instead of that it throws exception when you try to convert the null into integer value.
At the same time the Convert.ToInt32() handle implicitly when the type value is null.
Always recommended to use the Convert.Toint32() function for integer type conversion.
Thanks,
Senthil.
VulpesPosted Dec 10, 2011, 8:18 AM
Datta KharadPosted Dec 10, 2011, 8:02 AM
string str = "230";
int iNum = Convert.ToInt32(str);
int iNum2 = int.Parse(str);
//Result:- iNum=230
iNum2=230
//It will give same Result but in case string is null then int.Parse method cant handle null value.
string str = null;
int iNum = Convert.ToInt32(str);
int iNum2 = int.Parse(str);
//Result:- iNum=0;
iNum2= (it will throw error "Value cannot be null.")
The two give identical results, except where the string is null. Convert.ToInt32(null) returns zero, whereas Int32.Parse(null) throws an ArgumentNullException.
Satyapriya NayakPosted Dec 10, 2011, 2:43 AM
Int32.Parse (string s) method converts the string representation of a number to its 32-bit signed integer equivalent. When s is a null reference, it will throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.
Convert.ToInt32(string s) method converts the specified string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method. When s is a null reference, it will return 0 rather than throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.
Refer
http://www.codeproject.com/KB/cs/AgileWare_Convert_Int32.aspx
Thanks
Dharmesh SharmaPosted Dec 10, 2011, 2:24 AM
@ Convert.ToInt32() when you use if the object is null throw exception ,
in case of Int32.Parse() its show another excetion you can check it
thanks