C# If ... Else
The if statement lets your program make decisions by executing code only when a condition is true. You can add else if to check additional conditions, and else to run code when none of the conditions are true.
Conditions inside if statements must evaluate to a bool. This is a fundamental building block of program logic, letting programs respond differently depending on input or data.
if (condition) {
// code
} else if (condition2) {
// code
} else {
// code
}if, else if, else
An if statement runs a block only if its condition is true. else if lets you check another condition if the first was false, and else runs when none of the previous conditions matched.
Ternary operator
The ternary operator `condition ? valueIfTrue : valueIfFalse` is a compact way to write a simple if/else that returns a value.
using System;
class Program {
static void Main() {
int age = 20;
if (age >= 18) {
Console.WriteLine("Adult");
} else {
Console.WriteLine("Minor");
}
}
}AdultSince age is 20, which is >= 18, the if block runs.
using System;
class Program {
static void Main() {
int score = 75;
string grade = score >= 90 ? "A" : score >= 70 ? "B" : "C";
Console.WriteLine(grade);
}
}BThe ternary operator chains to check multiple ranges and assigns the matching grade.
Key points
- if runs code only when its condition is true.
- else if checks additional conditions in sequence.
- else runs when no previous condition was true.
- The ternary operator ?: is a shorthand for simple if/else.
