How to use int.TryParse

Learn how to use the int.TryParse in C#. C# TryParse code example.

When converting values in C#, we have three options : ParseConvert, and TryParse. My suggestion would be to use which method based on where the conversion is taking place. If you are validating input, an int parse or a convert will allow you to give specific error messages.

I am giving you a short example of int.TryParse:-

  1. public static void Main(string[] args)  
  2. {  
  3.     string str = "";  
  4.     int intStr; bool intResultTryParse = int.TryParse(str, out intStr);  
  5.     if (intResultTryParse == true)  
  6.     {  
  7.         Console.WriteLine(intStr);  
  8.     }  
  9.     else  
  10.     {  
  11.         Console.WriteLine("Input is not in integer format");  
  12.     }  
  13.     Console.ReadLine();  
  14. }  

 

In above Program str is not a integer. Whenever we use int.TryParse it returns boolean value.

First of all it validate your string. If your string is integer it returns True else False.

int.TryParse contain two arguments first is string and another is int(out type). If the input string is integer it returns 2nd arguments(out type int). Else it returns first argument(string).

untitled.JPG