Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to use int.tryparse in c# with example code

What does int.TryParse do in C#

The int.TryParse() is part of the system namespace and is used to convert number values from string format to integer format without throwing an exception. Compare to int.Parse and Convert.ToString() handles exceptions explicitly on its own, which helps prevent unwanted exceptions.


int.TryParse method signature in C#

public static bool TryParse(string userInput, out int result);

'userInput' is a number in the string data type. And the result is an output variable that holds the converted value if conversion is successful.


How int.TryParse method works in C# ?

The int.TryParse() method returns a bool value; if conversion is successful, it will return True, otherwise False. If the conversion is successful, it returns the integer value of the input given; otherwise, it returns 0 as the default.


How to use int.TryParse in C# with example


class Program
{
    static void Main()
    {
        string userInput = "1234";
        int number;

        if (int.TryParse(userInput, out number))
        {
            // The conversion was successful
            Console.WriteLine("Converted to integer: " + number);
        }
        else
        {
            // The conversion failed
            Console.WriteLine("Invalid input string " + userInput);
        }
    }
}
   
Output :
Converted to integer: 1234

Explanation of code and output: In this example, the input string "1234" is a valid integer number. The int.TryParse() method will return True, and the output parameter number will return an integer value of 1234.


Also, refer to the different scenarios mentioned below.

Scenario 1: If user input is "ABC", it will be considered invalid input, and the method will return False with an output value of 0.
Invalid input string ABC

Scenario 2:
If user input is "1234.0", It will be considered invalid input because the string contains the decimal separator "." and the method will return False with an output value of 0.
Invalid input string 1234.0

Scenario 3:
If user input is "99,999", It will be considered invalid input because the string contains the comma separator "," and the method will return False with an output value of 0.
Invalid input string 99,999

Scenario 4:
If user input is "-123" then the method will return True, and the output parameter will return a negative integer value.
Converted to integer: -123

Scenario 5:
If user input is "+999" then the method will return True, and the output parameter will return a positive integer value.
Converted to integer: 999


This post first appeared on Ask For Program, please read the originial post: here

Share the post

How to use int.tryparse in c# with example code

×

Subscribe to Ask For Program

Get updates delivered right to your inbox!

Thank you for your subscription

×