int.Parse() / int.TryParse()
Converts a string to an integer using int.Parse(), or attempts the conversion safely without throwing an exception using int.TryParse().
Syntax
// Converts a string to an int. Throws a FormatException if the conversion fails. int.Parse(string s) // Attempts the conversion. Returns true and the converted value on success. Does not throw an exception on failure. int.TryParse(string s, out int result) // Similar methods exist for other numeric types such as double and long. double.Parse(string s) double.TryParse(string s, out double result)
Method List
| Method | Description |
|---|---|
| int.Parse(string s) | Converts a string to an int. Throws a FormatException if the string cannot be converted. |
| int.TryParse(string s, out int result) | Attempts the conversion. Returns true and sets result to the converted value on success. Returns false and sets result to 0 on failure. |
| double.Parse(string s) | Converts a string to a double. |
| double.TryParse(string s, out double result) | Attempts to convert a string to a double. |
Sample Code
using System;
// Convert a string to an integer using int.Parse().
string numStr = "42";
int num = int.Parse(numStr);
Console.WriteLine(num + 10); // 52
// Convert safely using int.TryParse().
string input1 = "100";
string input2 = "abc"; // A string that cannot be converted to a number.
if (int.TryParse(input1, out int result1))
{
Console.WriteLine("Conversion succeeded: " + result1); // Conversion succeeded: 100
}
if (!int.TryParse(input2, out int result2))
{
Console.WriteLine("Conversion failed: " + result2); // Conversion failed: 0 (result is set to 0)
}
// A typical pattern for converting user input to an integer.
string userInput = "75";
if (int.TryParse(userInput, out int score))
{
Console.WriteLine($"Your score is {score}.");
}
else
{
Console.WriteLine("Please enter a valid number.");
}
// Your score is 75.
// Example using double.Parse().
double height = double.Parse("172.5");
Console.WriteLine(height); // 172.5
Notes
When converting user input or external data, it is strongly recommended to use int.TryParse() instead of int.Parse(). If the input is not a valid number, int.Parse() throws an exception and halts the program, whereas int.TryParse() lets you handle the failure safely.
Convert.ToInt32() can also convert a string to an integer, but it differs in that passing null returns 0 instead of throwing an exception. For details, see Convert.ToString() / Convert.ToInt32().
If you find any errors or copyright issues, please contact us.