0Pricing
C# Academy · Lesson

Type and Property Patterns

Match on shape and members.

The Type Pattern

A type pattern matches when the input is an instance of a given type. Written as just the type name in a switch arm, it tests the runtime type of the value.

This replaces clumsy is plus cast chains with a clean, single-expression check that also narrows the type for you.

object o = "hello";
string kind = o switch
{
    int    => "number",
    string => "text",
    _      => "unknown"
};
System.Console.WriteLine(kind);

Declaration Patterns

A declaration pattern adds a variable name after the type: string s. When it matches, the input is cast and bound to that variable.

You can then use the typed variable on the right side of the arm, accessing members specific to that type without an extra cast.

object o = "coddy";
string result = o switch
{
    string s => $"len {s.Length}",
    int n    => $"value {n}",
    _        => "other"
};
System.Console.WriteLine(result);

All lessons in this course

  1. switch Expressions
  2. Type and Property Patterns
  3. Relational and Logical Patterns
  4. List and Tuple Patterns
← Back to C# Academy