User Id :    Password :      New Member   Forgot Password  
 
Difference between int.Parse and Convert.ToInt32
Description Difference between int.Parse and Convert.ToInt32   No. of Views     1639
  Rating     0
Author Jalpesh Vadgama   Posted On     29 Nov 2010
Tags ASP.NET,C#    

Sample Code   Download Code

Difference between int.Parse and Convert.ToInt32

I know this post sound basic to most of people but still lots of people does not know this. So I decided to post a blog post for this. Both int.Parse and Convert.ToInt32 are used to convert string into the integer but Only difference between them is to Convert.ToInt32 handle null and returns ‘0’ as output and int.parse is not going to handle NULL and will give a Argument Null Exception. Here is the example for that both are almost same except handling null.
 

 string convertToInt = "12";
           string nullString = null;
           string maxValue = "32222222222222222222222222222222222";
           string formatException = "12.32";

           int parseResult;

           // It will perfectly convert interger
           parseResult= int.Parse(convertToInt);

           // It will raise Argument Null Exception
           parseResult= int.Parse(nullString);

           //It willl raise Over Flow Exception
           parseResult= int.Parse(maxValue);

           //It will raise Format Exception
           parseResult= int.Parse(formatException);


           //For Convert.ToInt32
        
           //It will perfectly convert integer
           parseResult= Convert.ToInt32(convertToInt);

           //It will ouput as 0 if Null string is there
           parseResult= Convert.ToInt32(nullString);

           //It will raise Over Flow Exception
           parseResult= Convert.ToInt32(maxValue);

           //It will raise Format Exception
           parseResult= Convert.ToInt32(formatException);

Hope this will help you understand the better but still there is third option available called int.TryParse which can handle all kind of exception and return result as Output Parameter.

 

About Author

About Author I am jalpesh vadgama an Microsoft MVP for Visual C# and BrainBench Certified ASP.NET Developer having more then 5 years of experience in .NET Technology.Please feel free to contact me for any queries via posting comments on my blog I will try to reply as early as possible. Please also visit my blog at http://jalpesh.blogspot.com/ Jalpesh Vadgama
No Photo
 
Country India
Company N/A
Home Page http://jalpesh.blogspot.com/

Rate this article

Rating options from poor, fair, good, very good to excelent.  
 

Comments

   
Write your comment here.
Comment
Verification Code