The examples in this topic show some different ways you can convert a string to an int in C#. Such a conversion can be useful when obtaining numerical input from a command line argument, for example.
Convert.ToInt32()
This example calls the ToInt32(String) method to convert an input string to an int . The program catches the two most common exceptions that can be thrown by this method. If the number can be incremented without overflowing the integer storage location, the program adds 1 to the result and prints the output.
int numVal = -1;
string input = Console.ReadLine();
// ToInt32 can throw FormatException or OverflowException.
try
{
numVal = Convert.ToInt32(input);
}
catch (FormatException e)
{
Console.WriteLine("Input string is not a sequence of digits.");
}
catch (OverflowException e)
{
Console.WriteLine("The number cannot fit in an Int32.");
}
finally
{
if (numVal < Int32.MaxValue)
{
Console.WriteLine("The new value is {0}", numVal + 1);
}
else
{
Console.WriteLine("numVal cannot be incremented beyond its current value");
}
}
Int32.Parse()
Another way of converting a string to an int is through the Parse methods of the System.Int32 struct. The above Convert.ToInt32 method uses Parse internally. If the string is not in a valid format, Parse throws an exception.
try
{
int m = Int32.Parse("abc");
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}