switch expressions; exhaustive checks with when (C# 6 emulation)
Emulate switch expressions with classic switch-return methods, add guard checks, and use default throws to catch unhandled cases at runtime.
switch expressions; exhaustive checks with when (C# 6 emulation) is a free C# Academy lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Plan: switch emulation
Goal: Mimic modern switch expressions in C# 6.
- Return values from classic switch
- Pre-check with guards
- Fail fast via default throw for exhaustiveness
Switch returning a value
A switch that returns a value acts like a switch expression. The default throw catches unknown values.
using System;
public enum Grade { A, B, C, D, F }
public class Program
{
static string Describe(Grade g)
{
switch (g)
{
case Grade.A: return "Excellent";
case Grade.B: return "Good";
case Grade.C: return "Average";
case Grade.D: return "Below average";
case Grade.F: return "Fail";
default: throw new ArgumentOutOfRangeException("g");
}
}
public static void Main(string[] args)
{
Console.WriteLine(Describe(Grade.A));
Console.WriteLine(Describe(Grade.F));
}
}
“when” via guards
Use guard checks (ifs) to emulate when clauses. Validate inputs first, then branch by ranges.
using System;
public class Program
{
// Emulate: switch(score) { case var s when s >= 90: ... } using pre-guards
static string LabelScore(int score)
{
if (score < 0 || score > 100) throw new ArgumentOutOfRangeException("score");
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
if (score >= 60) return "D";
return "F";
}
public static void Main(string[] args)
{
Console.WriteLine(LabelScore(92)); // A
Console.WriteLine(LabelScore(77)); // C
}
}
Exhaustive helper
Add a tiny Exhaustive.Unhandled helper and call it in default. Tests will fail when a new enum value is not handled.
using System;
public enum Status { New, Active, Closed }
public static class Exhaustive
{
public static Exception Unhandled(object x)
{
return new InvalidOperationException("Unhandled case: " + x);
}
}
public class Program
{
static int ToHttp(Status s)
{
switch (s)
{
case Status.New: return 201;
case Status.Active: return 200;
case Status.Closed: return 410;
default: throw Exhaustive.Unhandled(s);
}
}
public static void Main(string[] args)
{
Console.WriteLine(ToHttp(Status.Active)); // 200
}
}
Guards + switch on kind
Validate per-branch data with pre-guards, then switch on the discriminant. This mirrors “when” on cases.
using System;
public enum ShapeKind { Circle, Square }
public sealed class Shape
{
public ShapeKind Kind;
public double Radius; // for circle
public double Side; // for square
}
public class Program
{
static double Area(Shape s)
{
if (s == null) throw new ArgumentNullException("s");
// “when” guards (validate needed fields)
if (s.Kind == ShapeKind.Circle && s.Radius < 0) throw new ArgumentException("Radius must be >= 0");
if (s.Kind == ShapeKind.Square && s.Side < 0) throw new ArgumentException("Side must be >= 0");
switch (s.Kind)
{
case ShapeKind.Circle: return Math.PI * s.Radius * s.Radius;
case ShapeKind.Square: return s.Side * s.Side;
default: throw new InvalidOperationException("Unhandled shape: " + s.Kind);
}
}
public static void Main(string[] args)
{
Shape c = new Shape { Kind = ShapeKind.Circle, Radius = 2.0 };
Console.WriteLine("Area circle = " + Area(c));
}
}
Tips & pitfalls
Tips:
- Prefer small returning methods (single-responsibility)
- Keep default throwing to expose missing cases early
- Put guards before the switch; they act like when-conditions
Exhaustiveness emulation
Recap
Recap: Return from classic switch like a switch expression, add guards for “when”, and keep a default throw to surface missing cases.
Frequently asked questions
Is the “switch expressions; exhaustive checks with when (C# 6 emulation)” lesson free?
Yes — the full text of “switch expressions; exhaustive checks with when (C# 6 emulation)” is free to read here on the web, and the C# Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “switch expressions; exhaustive checks with when (C# 6 emulation)”?
Emulate switch expressions with classic switch-return methods, add guard checks, and use default throws to catch unhandled cases at runtime. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “switch expressions; exhaustive checks with when (C# 6 emulation)” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- is patterns; relational & logical patterns (C# 6 emulation)
- switch expressions; exhaustive checks with when (C# 6 emulation)
- Domain modeling with discriminated unions (records) — C# 6 emulation