int.Parse and TryParse
Learn safe number conversion with int.Parse and TryParse.
Converting with int.Parse
Console.ReadLine() always returns a string. When you need a number, the int.Parse method converts the string to an int. If the string is not a valid integer, it throws FormatException.
For example, int n = int.Parse("42"); assigns 42 to n. But int.Parse("hello") throws an error. That is why user input needs a safer approach, which we will see next.
Safe conversion with int.TryParse
The int.TryParse method returns true if the conversion succeeds and false otherwise, passing the result through an out parameter. It never throws an exception, which makes it much safer for user input.
For example, bool ok = int.TryParse(input, out int number); sets ok to true and fills number if input is valid. If not, ok becomes false and number stays zero. You can then branch safely with if (ok).
The out parameter
The out keyword is how a method returns more than one value. TryParse returns its main answer as a bool and passes the parsed number through an out parameter. You do not have to declare the variable before the call; you can declare it inline with out int number.
For example, if (int.TryParse(input, out int number)) { ... } both tries the conversion and declares number in one line. This is a flexible C# feature that keeps the code shorter.
Exercise Parse the number safely
Convert input into number using int.TryParse. If parsing succeeds, print number with Console.WriteLine; otherwise print "Invalid". Use an if on the return value of TryParse.
Show example solution
Declare int number; then check with if (int.TryParse(input, out number)) and print with WriteLine.
Example solution:
using System;
class Program
{
static void Main()
{
string input = "42";
int number;
if (int.TryParse(input, out number))
{
Console.WriteLine(number);
}
else
{
Console.WriteLine("Invalid");
}
}
}
Test yourself
-
What happens with an invalid string?
int n = int.Parse("hello");- Returns 0
- Returns null
- Throws FormatException
- Program freezes
Show answer
Throws FormatException — Correct! int.Parse throws FormatException on an invalid string.
-
TryParse call
string input = "42"; int number; bool ok = ____; Console.WriteLine(ok);Show answer
string input = "42"; int number; bool ok = int.TryParse(input, out number); Console.WriteLine(ok); -
Why prefer TryParse?
- Because it is faster
- Only for negative numbers
- Because it returns a string
- Because it does not throw
Show answer
Because it does not throw — Correct! TryParse does not throw, so it is safe for user input.