C# Practice Exercises

Switch Expression Calculator

Build a calculator with a C# switch expression.

Introduction

This exercise combines tuples, expressions, and exhaustive operator handling.

Matching the operator selects exactly one calculation, while the discard arm rejects unsupported values.

See how it works

Move the slider to change the day. The program jumps straight to the matching case, and to the default case when nothing matches.

Runnable C# example

C#
Run code →
Program.cs
using System;
class Program
{
    static double Calculate(double a, string op, double b) => op switch
    {
        "+" => a + b, "-" => a - b, "*" => a * b,
        "/" when b != 0 => a / b,
        _ => throw new ArgumentException("Unsupported operation")
    };
    static void Main() => Console.WriteLine(Calculate(6, "*", 7));
}
Result of running the code
42

Practice with the debugger

Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges