C# Convert String to Int

Conversion or change

How can you convert a variable of type string to a value of type integer? Fortunately, the C# programming language and .NET Framework provides some utility methods for this purpose. We describe the easiest way to convert strings to ints in the language.

This C# article shows how to convert a string into an int. It uses int.TryParse.

Example

To solve this problem, we will use the int.TryParse static method. When you call int.TryParse, you must pass it two arguments. The first argument is the string you want to convert. The second argument is modified with the 'out' keyword; it denotes the variable where the integer value will be stored upon completion of parsing. In other words, if you pass the string "123" as the first argument, the second argument will be filled with the integer 123.

Program that converts string to int [C#]

using System;

class Program
{
    static void Main()
    {
	// The input string.
	string variable = "123";
	// Use int.TryParse method.
	int value;
	int.TryParse(variable, out value);
	// Test for the correct value.
	if (value == 123)
	{
	    Console.WriteLine("Success");
	}
    }
}

Output

Success
Warning

Warnings. There are some difficult points regarding int.TryParse. If int.TryParse cannot parse the string as an integer, you will get the value 0 returned. Also, int.TryParse returns a bool that indicates success. This means you can test the result of int.TryParse in an if-expression, or store it in a local bool variable. Please see the article regarding int.TryParse for more details.

int.TryParse Method, Parse Integers Correctly int.Parse for Integer Conversion

Summary

The C# programming language

Although there are many ways to convert strings to integers in the C# language, some are better than others in certain program contexts. As a general rule, however, the int.TryParse method is excellent for most programs.

Cast Examples
.NET