How to use int.TryParse

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:-

public static void Main(string[] args)
{
    string str = "";
    int intStr;
    bool intResultTryParse = int.TryParse(str, out intStr);
    if (intResultTryParse == true)
    {
        Console.WriteLine(intStr);
    }
    else
    {
        Console.WriteLine("Input is not in integer format");
    }
    Console.ReadLine();
}

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

Ebook Download
View all
Learn
View all