C# Convert String, Int

Convert or change

A string can be converted to an integer (int). The C# language provides some utility methods for this purpose. We describe an easy way to convert strings to ints. This approach avoids exceptions when a string cannot be converted.


Int keyword

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.

Out ParameterStatic Method

Note:Out denotes the variable where the integer value will be stored upon completion of parsing.

So:If you pass the string "123" as the first argument, the second argument will be filled with the integer 123.

Int Type
C# program that converts string to int

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)


Warning: exclamation mark

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.

Bool Type

Note:This means you can test the result of int.TryParse in an if-expression, or store it in a local bool variable.



There are many ways to convert strings to integers in the C# language. Some are better than others in certain program contexts. But as a general rule the int.TryParse method is excellent for most programs.


C#: Cast