Skip to content

Pattern Matching

The is Operator

Use is to test whether a value is of a given type at runtime:

int Describe(Shape! obj)
{
if (obj is Circle)
{
return 1;
}
return 0;
}

is returns bool and works with custom types, interfaces, and primitive types.

Binder Pattern

Combine a type test with a variable binding:

if (obj is Dog d)
{
Console.WriteLine(d.Name);
}

The variable d is only in scope inside the if block, typed as Dog.

The as Operator

Use as to cast a reference to a more specific type:

Circle? circle = shape as Circle;
if (circle != null)
{
Console.WriteLine($"{circle.radius}");
}

Type Switch

Use switch with type case labels to test a value against multiple types. The compiler detects the type switch automatically:

switch (value)
{
case int i:
Console.WriteLine($"{i}");
break;
case string s:
Console.WriteLine(s);
break;
}

Value Switching

Standard switch works for integer, float, and string value patterns. Use break to exit a case, or return to leave the function:

string DescribeDay(int day)
{
switch (day)
{
case 0: return "Monday";
case 1: return "Tuesday";
default: return "other";
}
}

When not returning, use break to prevent fallthrough:

int category = 0;
switch (n)
{
case 1:
category = 10;
break;
case 2:
category = 20;
break;
default:
category = -1;
break;
}

Float Switch

switch (temperature)
{
case 0.0: return "freezing";
case 100.0: return "boiling";
case -273.15: return "absolute zero";
default: return "other";
}

String Switch

switch (command)
{
case "start": return 1;
case "stop": return 2;
case "pause": return 3;
default: return 0;
}

Range Patterns

Integer switch statements support range patterns with the .. operator. A range case matches any value from the low bound to the high bound (inclusive):

switch (score)
{
case 90..100: return "A";
case 80..89: return "B";
case 70..79: return "C";
case 60..69: return "D";
default: return "F";
}

Ranges can be mixed with exact cases:

switch (n)
{
case 0: return "zero";
case 1..10: return "small";
case 11..100: return "medium";
default: return "large";
}

Negative ranges are supported:

switch (temp)
{
case -40..-1: return "below zero";
case 0: return "freezing";
case 1..100: return "above zero";
}

When Guards

Type switch cases support when guard clauses for additional filtering:

switch (shape)
{
case Circle c when c.radius > 10:
return "large circle";
case Circle c:
return "small circle";
case Rectangle r when r.width == r.height:
return "square";
default:
return "other";
}

The guard expression is evaluated after the type match succeeds. If the guard is false, the case is skipped and the next case is tried.

Combining is with Ternary

int x = 42;
int result = x is int ? 1 : 0;

Polymorphic is

is works with GC references and inheritance hierarchies:

type Animal { int age; }
type Dog : Animal { string name; }
Animal? a = new Dog();
if (a is Dog d)
{
// d is bound as Dog
}