Conditionals are how your program makes decisions. Think about it โ every app you use makes decisions all the time. "If the user is logged in, show the dashboard. Otherwise, show the login page." That is a conditional.
The if Statement
The if statement checks a condition and runs the code inside the curly braces
only if the condition is true:
int age = 20;
if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
The condition goes inside the parentheses. If it evaluates to true, the code
block runs. If it is false, C# skips it entirely.
if-else
Sometimes you want to do one thing if the condition is true, and something else if it
is false. That is where else comes in:
int temperature = 35;
if (temperature > 30)
{
Console.WriteLine("It is hot outside!");
}
else
{
Console.WriteLine("The weather is nice.");
}
One of these two blocks will always run โ either the if block or the else block.
Never both.
if-else if-else
When you have more than two options, you chain else if conditions together:
int score = 75;
if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B");
}
else if (score >= 70)
{
Console.WriteLine("Grade: C");
}
else if (score >= 60)
{
Console.WriteLine("Grade: D");
}
else
{
Console.WriteLine("Grade: F");
}
C# checks each condition from top to bottom. As soon as it finds one that is true,
it runs that block and skips the rest. If none of them are true, it runs the final
else block.
Nested Conditionals
You can put if statements inside other if statements. This is called
nesting:
bool hasTicket = true;
int age = 15;
if (hasTicket)
{
if (age >= 18)
{
Console.WriteLine("Welcome to the concert!");
}
else
{
Console.WriteLine("Sorry, you must be 18 or older.");
}
}
else
{
Console.WriteLine("You need a ticket to enter.");
}
Be careful with deep nesting โ it can make your code hard to read. If you find yourself going three or four levels deep, there is usually a cleaner way to write it.