Every program makes decisions. Do this if it's raining, do that if it's sunny. In C#, decisions are made with if, else if, and else.
The if Statement
The simplest building block: if a condition is true, run the code inside the braces. If not, skip it.
using System;
class Program {
static void Main() {
int age = 18;
if (age >= 18) {
Console.WriteLine("You can vote!");
}
}
}
Try it Yourself โ
else if and else
When one condition isn't enough, chain with else if. The first match wins; the rest are ignored. else catches everything that didn't match.
using System;
class Program {
static void Main() {
int score = 85;
if (score >= 90) {
Console.WriteLine("Grade A");
} else if (score >= 75) {
Console.WriteLine("Grade B");
} else if (score >= 50) {
Console.WriteLine("Grade C");
} else {
Console.WriteLine("Grade F");
}
}
}
Try it Yourself โ
Nested Conditions
You can put an if inside another if. This is nesting โ useful when you need to check a second condition only after the first passes.
using System;
class Program {
static void Main() {
int x = 10, y = 5;
if (x > 0) {
if (y > 0) {
Console.WriteLine("Both are positive");
}
}
}
}
Try it Yourself โ
Boolean Expressions
In C#, the condition has to be a bool โ either true or false. No tricks like in some languages where numbers count as true or false.
using System;
class Program {
static void Main() {
bool isRaining = true;
if (isRaining) {
Console.WriteLine("Take an umbrella");
} else {
Console.WriteLine("Enjoy the sun");
}
}
}
Try it Yourself โ