User Id :    Password :      New Member   Forgot Password  
 
int.Parse and Convert.ToInt32 and int.TryParse in cSharp
Description int.Parse and Convert.ToInt32 and int.TryParse   No. of Views     2471
  Rating     0
Author Gaurav   Posted On     09 Feb 2014
Tags C# 4.0,C# : How To    

Sample Code   Download Code

int.Parse and Convert.ToInt32 and int.TryParse all three are used to convert string into the integer.
 
When we try to convert a null string Convert.ToInt32 handle this null value and returns ‘0’ as output. Also if the input in not a valid integer value, it throws exception.
 
int.parse does not handle NULL and will give a Argument Null Exception.  Also if the input in not a valid integer value, it throws exception.
 
The int.TryParse method converts string into int. This method hanles all kind of exception and returns result as output parameter even if the input is invalid.
int.TryParse takes 2 arguments, first a boolen  value that tells wheather the conversion was successfull or not and second parameter is an out parameter that contains the final output.
 
namespace Dynamic
{
    class Program
    {
        public void Check()
        {
            string IntegerValue = "100";
            string InvalidString = "A100.B";
            string nullString = null;     
            int Output;
            
	// ---- Testing int.Parse

        Output = int.Parse(IntegerValue); //Perfect works      
        Output = int.Parse(nullString);//Null Exception
        Output = int.Parse(InvalidString);//Format Exception
      
	// ---- Testing Convert.ToInt32

        Output = Convert.ToInt32(IntegerValue);//Perfect works      
        Output = Convert.ToInt32(nullString);//Output will be "0" handle null exception
        Output = Convert.ToInt32(InvalidString);//Format Exception

        Output = 0;       
        
	// ---- Testing int.TryParse

	var status =  int.TryParse(IntegerValue, out Output);
	// Here status will be true and Output will be 100... Its a successfull conversion
        
	var status =  int.TryParse(nullString, out Output);
	// Here status will be false and Output will be 0(default value that was assigned before conversion)
        
	var status =  int.TryParse(InvalidString, out Output);
	// Here status will be false and Output will be 0(default value that was assigned before conversion)
        }

        static void Main(string[] args)
        {
            Program prog = new Program();
            prog.Check();
        }

    }
}

 

Hope that helps...

Thanks,

About Author

About Author I am as simple as c#. Gaurav
No Photo
 
Country India
Company N/A
Home Page N/A

Rate this article

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

Comments

   
Write your comment here.
Comment
Verification Code