Conditionals
Conditionals in C#
C# provides several powerful branching constructs.
if / else if / else Classic conditional branching with boolean expressions:
csharp
if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else grade = "C";switch expressions (C# 8+) A concise, exhaustive alternative to switch statements:
csharp
string label = code switch {
1 => "One",
2 => "Two",
_ => "Other"
};Pattern matching C# 9+ enhanced patterns let you match on type, value, and structure:
csharp
string desc = obj switch {
int n when n > 0 => "positive int",
string s => $"string: {s}",
null => "null",
_ => "other"
};Ternary operator
csharp
string result = x > 0 ? "positive" : "non-positive";Key points:
- Switch expressions require exhaustiveness — use
_as a catch-all. - Pattern matching eliminates many explicit
isand cast chains. - The null-coalescing operator
??is a concise alternative to null-checking ternaries.
Code Examples
if/else and ternarycsharp
using System;
class Conditionals {
static void Main() {
int score = 75;
string grade;
if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else if (score >= 70) grade = "C";
else grade = "F";
Console.WriteLine($"Grade: {grade}");
bool passing = score >= 60;
Console.WriteLine(passing ? "Passing" : "Failing");
string name = null;
Console.WriteLine(name ?? "Anonymous");
}
}The null-coalescing operator ?? returns the left operand if non-null, otherwise the right operand.
switch expression and pattern matchingcsharp
using System;
class SwitchDemo {
static string Classify(object obj) => obj switch {
int n when n > 0 => $"positive int: {n}",
int n => $"non-positive int: {n}",
string s when s.Length > 5 => $"long string",
string s => $"short string: {s}",
null => "null",
_ => "other"
};
static void Main() {
Console.WriteLine(Classify(42));
Console.WriteLine(Classify(-3));
Console.WriteLine(Classify("hi"));
Console.WriteLine(Classify("hello world"));
Console.WriteLine(Classify(null));
}
}Pattern matching in switch expressions can test type, value, and conditions in a single expression.
Quick Quiz
1. What is the C# 8+ switch expression discard pattern?
2. What does the `??` operator do?
Was this lesson helpful?