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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Dharmesh SharmaRank #1,974 · 741 reputationPosted Dec 9, 2011, 9:24 PM EST
@ 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
Satyapriya NayakRank #47 · 31.5K reputationPosted Dec 9, 2011, 9:43 PM EST
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
Datta KharadRank #2,135 · 668 reputationPosted Dec 10, 2011, 3:02 AM EST
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.
VulpesRank #55 · 29.2K reputationPosted Dec 10, 2011, 3:18 AM EST
SenthilkumarRank #387 · 6.5K reputationPosted Dec 10, 2011, 3:19 AM EST
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.
Posted Dec 10, 2011, 4:24 AM EST