For training related to .net,OOPS,design patterns, MVC,WCF and .net fundamentals
contact at sukeshmarla@gmail.com or Click Here

08 May 2011

int.Parse vs Convert.ToInt32 vs int.TryParse

All int.Parse and Convert.ToInt32 and int.TryParse are used to convert string into the integer.

  • Convert.ToInt32 handle null and returns ‘0’ as output.
  • int.parse is not going to handle NULL and will give a Argument Null Exception. 
  • int.TryParse also take a second integer parameter which will be an output parameter.This method hanles all kind of exception and returns result as output parameter.

      
      string ValidInteger = "45";
      string nullString = null;
      string InvalidString="45.1";

      int Result;
      
      #region int.Parse
         // It will perfectly convert interger
         Result= int.Parse(ValidInteger);
  
        // It will raise Argument Null Exception
        Result= int.Parse(nullString);

       //It will raise Format Exception
       int.Parse(InvalidString);

     #end region

     #region Convert.ToInt32
       //It will perfectly convert integer
       Result= Convert.ToInt32(ValidInteger);

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

       //It will raise Format Exception
       Result= Convert.ToInt32(InvalidString);
     #end region

    #region int.TryParse
      
       Result=-1; 
      
       //Value of Result will be 45
       int.TryParse(ValidInteger,out Result);

       //Value of Result will be -1
       int.TryParse(nullString,out Result);

       //Value of Result will be -1
       int.TryParse(InvalidString,out Result);
     #end region