Tutorials / C# for Beginners / Conditionals and switch expressions

Conditionals and switch expressions

13 min read csharp
Course contents (16 lessons)
  1. Getting started
  2. Installing the .NET 10 SDK and checking it works
  3. Your first console app and top-level statements
  4. The building blocks
  5. Variables and basic types
  6. Working with strings and interpolation
  7. Reading input and writing output
  8. Making decisions and repeating work
  9. Conditionals and switch expressions
  10. Loops: for, while, do and foreach
  11. Collections and methods
  12. Arrays and List of T
  13. Writing your own methods
  14. Objects and classes
  15. Classes and objects
  16. Properties, encapsulation and object initialisers
  17. Handling null safely
  18. Errors and files
  19. Exceptions: try, catch, finally and throw
  20. Reading and writing files
  21. Final project: expense tracker
  22. Expense tracker, part 1: planning, model and storage
  23. Expense tracker, part 2: the menu and summaries

Programs that choose

So far every program ran the same lines in the same order. Real programs make decisions. A shop gives a discount only above a certain total. A login accepts a password only if it matches. In C# the basic tool for this is if.

if, else if, else

An if statement has a condition in brackets. The condition must be a bool. If it is true, the block in curly braces runs.

int score = 72;

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("Fail");
}

C# checks the conditions from top to bottom and runs only the first block that matches. With a score of 72, the first two checks fail, the third passes, and it prints "Grade C". The order matters. If you checked score >= 50 first, every passing score would be a C.

Comparison and logical operators

The comparison operators are ==, !=, <, >, <= and >=. Combine conditions with && (and), || (or) and ! (not). Both && and || stop early. If the left side of an && is false, the right side is never evaluated. That is useful and safe: name != null && name.Length > 0 never touches Length on a null.

The ternary operator

For a simple choice between two values, the ternary operator is shorter: condition ? valueIfTrue : valueIfFalse.

int age = 17;
string label = age >= 18 ? "adult" : "minor";

Use it for simple cases only. Nested ternaries are hard to read, and I avoid them.

switch statements and switch expressions

When one value can match many cases, a switch is cleaner than a long chain of else if. C# has the older switch statement and the newer switch expression. The expression produces a value, and I prefer it.

Console.Write("Enter a day number (1-7): ");
int.TryParse(Console.ReadLine(), out int day);

string name = day switch
{
    1 => "Monday",
    2 => "Tuesday",
    3 => "Wednesday",
    4 => "Thursday",
    5 => "Friday",
    6 or 7 => "Weekend",
    _ => "Not a valid day"
};
Console.WriteLine(name);

Console.Write("Enter your score: ");
int.TryParse(Console.ReadLine(), out int score);

string grade = score switch
{
    >= 90 => "A",
    >= 75 => "B",
    >= 50 => "C",
    >= 0  => "Fail",
    _     => "Invalid score"
};
Console.WriteLine($"Grade: {grade}");

// The older switch statement
switch (day)
{
    case 6:
    case 7:
        Console.WriteLine("Enjoy your weekend.");
        break;
    default:
        Console.WriteLine("Back to work.");
        break;
}

Walking through it

In the switch expression, each line is a pattern, then =>, then the result. The first pattern that matches wins. 6 or 7 matches either number. The underscore _ is the discard pattern. It matches anything, so it works as the default case. The compiler warns you if you forget it and some values would not be handled.

The second switch uses relational patterns such as >= 90. This replaces the whole if-else chain from earlier in four short lines. Order still matters, because the first match wins.

The old statement form needs a break at the end of every case. If you forget, the compiler gives an error. C# does not allow falling from one case into the next, unlike some other languages. Two empty case labels stacked together, like case 6: case 7:, share one body.

Common mistakes

  • Using = instead of ==. One assigns, two compare. In C# the compiler usually catches this because assignment is not a bool.
  • Missing braces. An if without braces controls only the next line. Add braces always. It prevents bugs when you add a second line later.
  • Wrong order of conditions. Test the most specific condition first.
  • Forgetting the default case in a switch expression. An unmatched value throws an exception at runtime.

Try it yourself

  1. Write a program that reads a temperature in Celsius and prints "freezing", "cold", "warm" or "hot" using a switch expression with relational patterns.
  2. Ask for a year and print whether it is a leap year. A leap year is divisible by 4, but not by 100 unless it is also divisible by 400.
  3. Rewrite the grade example using only if and else if, then compare the two versions. Which one do you find easier to read?
csharp
Console.Write("Enter a day number (1-7): ");
int.TryParse(Console.ReadLine(), out int day);

string name = day switch
{
    1 => "Monday",
    2 => "Tuesday",
    3 => "Wednesday",
    4 => "Thursday",
    5 => "Friday",
    6 or 7 => "Weekend",
    _ => "Not a valid day"
};
Console.WriteLine(name);

Console.Write("Enter your score: ");
int.TryParse(Console.ReadLine(), out int score);

string grade = score switch
{
    >= 90 => "A",
    >= 75 => "B",
    >= 50 => "C",
    >= 0  => "Fail",
    _     => "Invalid score"
};
Console.WriteLine($"Grade: {grade}");

// The older switch statement
switch (day)
{
    case 6:
    case 7:
        Console.WriteLine("Enjoy your weekend.");
        break;
    default:
        Console.WriteLine("Back to work.");
        break;
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account