If you are C# developer, there can be times when you may need to convert the "string" data type into "int" data type then C# already have to built-in functions for it, these are int.Parse() & int.TryParse() are used to convert string to int in C#, so we will discuss each one of these one by one.

Converting string to int in C# 

Suppose we want to convert string "90" into int then we can use int.Parse or int.TryParse. You can use Parse or TryParse methods on the numeric type you expect the string contains, such as the System.Int32 type.

The Parse and TryParse methods ignore white space at the beginning and at the end of the string, but all other characters must be characters that form the appropriate numeric type (int, long, ulong, float, decimal, etc.). Any white space within the characters that form the number cause an error.

Here is the working example in Console App in C# using int.Parse()

using System;

namespace String2Int
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "90";
            int num = int.Parse(text);
            Console.WriteLine(num);
        }
    }
}

convert-string-to-int-csharp-min.png

Using int.TryParse(), when you use this method, you can give your code some options for how to handle errors or strings that don’t aren’t numbers and can’t be converted.

using System;

namespace String2Int
{
    class Program
    {
        static void Main(string[] args)
        {
            //string text = "90";
            //int num = int.Parse(text);
            //Console.WriteLine(num);
            //Console.WriteLine(num + 10);


            string test = "100";
            int number;
            //trparse gives output in second argument and result as bool
            bool res = int.TryParse(test, out number);
            Console.WriteLine(number);
        }
    }
}

Output

convert-string-to-int-using-tryparse-csharp-min.png

As you can see in the above code, TryParse has a little bit confusing output, it gives output result in the second argument while the main result is a boolean value(returns true or false based on its success).

// TryParse returns true if the conversion succeeded
// and stores the result in j.
int j;
if (Int32.TryParse("-105", out j))
    Console.WriteLine(j);
else
    Console.WriteLine("String could not be parsed.");
// Output: -105

TryParse never throws an exception—even on invalid input and null. It is overall preferable to int.Parse in most program contexts.

Difference between Int.Parse and Int.TryParse

The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed.

The int.Prase() method throws three different types of exceptions depends on the data provided.

  • If the parameter value is null, then it will throw ArgumentNullException
  • If the parameter value is other than integer value or not in proper format, it will throw FormatException.
  • if the parameter value is out of integer ranges, then it will throw  OverflowException.

In case of int.TryParse() method, when it converts the string representation of a number to an integer; it set the out variable with the result integer and returns true if successfully parsed, otherwise false.

One of the important point to be noted here is incase of int.TryParse() there won't be any exception, it returns the result as 0 & method as false.

Which should I use when?

If you've got a string, and you expect it always to be an integer (say, if some web service is handing you an integer in string format), you should use Int32.Parse()

If you're collecting input from a user, you'd generally use Int32.TryParse(), since it allows you more fine-grained control over the situation when the user enters invalid input.

Personally, I recommend using TryParse in most situations. It is faster on errors and is a good default choice for parsing.

You may also like to read:

C# String

C# Datetime