C# Input, Conversion, and Validation
Accept text from a user, convert it safely, and keep invalid input from becoming invalid program state.
Before this lesson
- Variables and numeric types
- Strings
- Basic method calls
Read a line from standard input
Distinguish parsing from casting
Validate both format and business rules before using a value
The short answer
Console.ReadLine reads text. When the program needs a number or another type, TryParse tests the text and produces a converted value without crashing on ordinary invalid input.
Programs receive uncertain data
Values written in source code are under the programmer's control. Input from a keyboard, file, form, or network request is not. It may be blank, misspelled, too large, or shaped differently from what the program expects. Treat external input as text that must earn its way into the program's trusted state.
Console.ReadLine waits for a line and returns its text without the Enter key. The console does not know that 42 is intended as an age; it returns the two characters as a string. Conversion gives the program a numeric value on which arithmetic is meaningful.
Parsing is not casting
A cast converts between compatible representations already understood by the type system, such as int to double. Parsing interprets the characters in text according to a format. The string "42" is not an int hidden behind a label, so (int)input is not the right operation.
int.Parse returns an integer when the text is valid but throws an exception when it is not. int.TryParse instead returns true or false and places a successful result in an out variable. Invalid user typing is expected, so TryParse usually gives console and form code a clearer control flow.
| Operation | Use when | Failure behavior |
|---|---|---|
| Cast | Types have a defined conversion | May lose data or throw for an invalid runtime cast |
| Parse | Text is guaranteed by a trusted format | Throws when text is invalid |
| TryParse | Text may be invalid user or external input | Returns false without an exception |
| Convert | You need its specific null/conversion rules | Varies by conversion |
Format validation is only the first gate
TryParse answers whether text can represent an int. It does not answer whether the value makes sense for your program. -8 is a valid integer format but not a valid item quantity. After parsing, apply domain rules such as a minimum, maximum, allowed set, or relationship to another value.
The example uses && so every required condition must be true. C# evaluates the parts from left to right and stops as soon as the whole expression must be false. That means age rules are considered only after parsing succeeded.
using System;
class Program
{
static void Main()
{
string quantityText = "12";
int quantity;
if (!int.TryParse(quantityText, out quantity))
{
Console.WriteLine("Quantity must be a whole number.");
}
else if (quantity < 1 || quantity > 50)
{
Console.WriteLine("Quantity must be between 1 and 50.");
}
else
{
Console.WriteLine($"Accepted quantity: {quantity}");
}
}
}Expected output
Accepted quantity: 12
Give feedback that helps the next attempt
A useful validation message states the requirement: Enter a whole number from 1 to 50. A vague message such as Invalid input forces the user to guess. Do not echo secrets or internal exception details into user-facing messages.
Interactive applications often repeat the prompt until input is valid or the user cancels. That repetition needs a loop, which comes soon. For now, one attempt is enough to understand the boundary: raw text enters, parsing checks its shape, domain validation checks its meaning, and only then does the program act on it.
Good habits
- Validate at the boundary where uncertain data enters the program.
- Keep the original text when a helpful error message or retry needs it.
- Use culture-aware parsing when accepting dates or decimal numbers from real users in different locales.
Quick knowledge check
Answer before you reveal.
01Does int.TryParse("-5", out value) return false?
No. -5 is a valid integer format. A separate business rule must reject it when negative values are not allowed.
02Why not catch an exception from int.Parse for every invalid keystroke?
Invalid interactive input is expected rather than exceptional. TryParse represents that normal branch directly and avoids using exceptions for routine control flow.
Practice challenge
Now build it without copying.
Read a temperature from the compiler's Program input box. Accept it only when it is a number from -100 through 100, then print the Fahrenheit conversion; otherwise print the exact allowed range.
You are done when
- Non-numeric input does not crash the program
- A numeric value outside the range is rejected separately
- The conversion runs only after both checks pass
Stretch: Accept decimal temperatures with double.TryParse and format the result to one decimal place.
Open challenge in playgroundLesson checkpoint
One small step locks it in
Mark this lesson complete, then keep the momentum going.
Clear up the details
Frequently asked questions
What happens if Console.ReadLine reaches the end of input?
It can return null. The course compiler usually supplies entered lines, but production code should account for the input stream ending.
Can TryParse declare the result inline?
Modern C# supports if (int.TryParse(input, out int age)). This course sometimes declares the variable first so the two outputs—success flag and parsed value—are easier to see.
How do I parse dates and decimals safely?
DateTime, decimal, double, and other types provide TryParse methods. Real applications should also decide which culture and exact formats they accept.