The if Statement
The if statement evaluates a boolean expression. If it is true, the body executes. The body can be a single statement or a block surrounded by curly braces. Always use braces to avoid bugs when adding extra lines later.
int temperature = 35;
if (temperature > 30)
{
Console.WriteLine("It's hot outside!");
}if / else and else if
Add an else block to handle the false case. Chain multiple conditions with else if. Only the first matching block executes; the rest are skipped.
int score = 72;
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");Nested if Statements
You can place an if inside another if. Keep nesting shallow (maximum 2โ3 levels) to maintain readability. Consider early-return patterns or guard clauses to avoid deep nesting.
static void ProcessOrder(Order? order)
{
if (order == null) return; // guard
if (!order.IsValid) return; // guard
if (order.Total <= 0) return; // guard
// Happy path โ no deep nesting
Console.WriteLine($"Processing order #{order.Id}");
}Pattern Matching in if
C# supports type patterns (is TypeName variable), relational patterns, and logical patterns (and, or, not) directly inside if conditions.
object obj = 42;
// Type pattern
if (obj is int number)
Console.WriteLine($"Integer: {number}");
// Relational pattern
int age = 25;
if (age is >= 18 and <= 65)
Console.WriteLine("Working age");
// Negation pattern
string? name = null;
if (name is not null)
Console.WriteLine(name);