How to: Convert a string to an int (C# Programming Guide)
These examples show some different ways you can convert a string to an int. Such a conversion can be useful when obtaining numerical input from a command line argument, for example. Similar methods exist for converting strings to other numeric types, such as float or long. The table below lists some of those methods.
Numeric Type |
Method |
---|---|
decimal |
|
float |
|
double |
|
short |
|
int |
|
long |
|
ushort |
|
uint |
|
ulong |
Example
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, FormatException and OverflowException. If the number can be incremented without overflowing the integer storage location, the program adds 1 to the result and prints the output.
static void Main(string[] args)
{
int numVal = -1;
bool repeat = true;
while (repeat == true)
{
Console.WriteLine("Enter a number between −2,147,483,648 and +2,147,483,647 (inclusive).");
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");
}
}
Console.WriteLine("Go again? Y/N");
string go = Console.ReadLine();
if (go == "Y" || go == "y")
{
repeat = true;
}
else
{
repeat = false;
}
}
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
// Sample Output:
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
// 473
// The new value is 474
// Go again? Y/N
// y
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
// 2147483647
// numVal cannot be incremented beyond its current value
// Go again? Y/N
// Y
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
// -1000
// The new value is -999
// Go again? Y/N
// n
// Press any key to exit.
Another way of converting a string to an int is through the Parse or TryParse methods of the System.Int32 struct. The ToUInt32 method uses Parse internally. If the string is not in a valid format, Parse throws an exception whereas TryParse does not throw an exception but returns false. The examples below demonstrate both successful and unsuccessful calls to Parse and TryParse.
int numVal = Int32.Parse("-105");
Console.WriteLine(numVal);
// Output: -105
// 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
try
{
int m = Int32.Parse("abc");
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
// Output: Input string was not in a correct format.
string inputString = "abc";
int numValue;
bool parsed = Int32.TryParse(inputString, out numValue);
if (!parsed)
Console.WriteLine("Int32.TryParse could not parse '{0}' to an int.\n", inputString);
// Output: Int32.TryParse could not parse 'abc' to an int.
See Also
Tasks
How to: Determine Whether a String Represents a Numeric Value (C# Programming Guide)