There are different ways in C# to convert a String variable to an Integer. Following are the different methods you can use to convert String to Int. One is you can use the ToInt32 method from the Convert Class to do this conversion. Secondly, you can use the Parse Method from the System.Int32 Struct and thirdly the TryParse from System.Int32
Method 1: Using Convert
Here is the first method using the Convert.ToInt32
Console.WriteLine("Enter a number ");
string input = Console.ReadLine();
int numVal = -1;
numVal = Convert.ToInt32(input);
Method 2: Using Parse
Another way of converting a string to an int is through the Parse method of the System.Int32 struct.
int numVal = Int32.Parse("-105");
Console.WriteLine(numVal);
// Output: -105
Method 3: Using TryParse
Here this is the third way to do it using the TryParse method of the System.Int32 struct.
// TryParse returns true if the conversion succeeded
// and stores the result in the specified variable.
int j;
bool result = Int32.TryParse("-105", out j);
if (true == result)
Console.WriteLine(j);
else
Console.WriteLine("String could not be parsed.");
// Output: -105
