C# Tutorial · Control Flow · Lesson 8 of 22

C# If Else and Switch

Conditions, switch statements and switch expressions with patterns.

if / else

Example 1
int hour = 15;
if (hour < 12)
    Console.WriteLine("Good morning");
else if (hour < 18)
    Console.WriteLine("Good afternoon");
else
    Console.WriteLine("Good evening");

string day = "Sat";
switch (day)
{
    case "Sat":
    case "Sun":
        Console.WriteLine("Weekend");
        break;
    default:
        Console.WriteLine("Weekday");
        break;
}

Output

Good afternoon
Weekend

Run this on your computer — see “Get Started” for setup.

switch expressions and patterns

Modern C# has switch expressions that return values and match patterns — types, ranges with relational patterns, and property patterns:

Example 2
static string Grade(int score) => score switch
{
    >= 90 => "A",
    >= 80 and < 90 => "B",
    >= 70 => "C",
    _ => "F",
};

static string Describe(object o) => o switch
{
    int n when n < 0 => "negative int",
    int n => $"int {n}",
    string { Length: 0 } => "empty string",
    string s => $"string '{s}'",
    null => "null",
    _ => o.GetType().Name,
};

Console.WriteLine($"{Grade(95)} {Grade(85)} {Grade(72)} {Grade(10)}");
foreach (var o in new object?[] { 42, -1, "", "hi", null, 3.5 })
    Console.WriteLine(Describe(o!));

Output

A B C F
int 42
negative int
empty string
string 'hi'
null
Double

Run this on your computer — see “Get Started” for setup.

Test yourself

Which symbol is the discard (default) pattern in a switch expression?

  1. default
  2. _
  3. *
  4. else
Show answer

Answer: _