11. C# (Parsing)
Source: Dev.to
The Real Goal of This Lesson
The goal of this lesson is not to memorize int.Parse; the real point is to understand that a computer never trusts user input. Parsing is an explicit, intentional step that takes responsibility for interpreting a string as a specific type.
Console.ReadLine()always returns a string (never throws an exception).- From the computer’s perspective the user might type:
123-5ABC12.5- nothing at all (just Enter)
Because the compiler cannot predict what the user will enter, C# makes a deliberate design choice: do not guess.
int number = Console.ReadLine(); // Compile-time error
Console.ReadLine() returns a string, while number expects an int; this violates the type contract. The compiler cares only about types, not about possible runtime values. If we want to treat user input as a number, we must explicitly say so—this is called parsing.
What is parsing?
Parsing is the act of interpreting a string as another type:
"123"→int 123"true"→bool true"2026-01-01"→DateTime
Parsing is not automatic; it must be invoked intentionally.
Basic example
using System;
class Program
{
static void Main()
{
Console.WriteLine("Enter a number:");
var input = Console.ReadLine(); // always string
int number = int.Parse(input); // string → int
Console.WriteLine(number + 10);
}
}
Step‑by‑step reasoning
- User enters
5. inputbecomes"5"(a string).int.Parse("5")produces5(anint).number + 10results in15.
If int.Parse cannot interpret the string (e.g., int.Parse("ABC")), execution fails at runtime (covered in later lessons).
Why C# Forces This Step
C# follows the philosophy: “Risky operations must be explicit.” Converting a string to a number is risky because the string might:
- Not represent a number.
- Be empty.
- Be malformed.
Therefore, C# refuses to guess and requires the developer to consciously state the intention:
int number = int.Parse(input); // explicit conversion
Common misconceptions
- Incorrect mindset: “
ReadLine()might return a number; the compiler should figure it out.” - Correct mindset: “User input is always a string. If I need a number, I must explicitly parse it.”
Unresolved problem
int.Parse("ABC"); // Runtime failure
This error occurs at runtime, not compile time. Subsequent topics will cover how to handle such cases safely:
TryParse- Exceptions
- Preventing runtime crashes
Remember: Console.ReadLine() always returns a string.