Skip to content

Type pattern

Context: The type pattern tests whether an expression is of a specified type and, if so, assigns it to a new variable.

object obj = "Hello";
if (obj is string s)
{
Console.WriteLine(s.Length);
}
object obj = 42;
if (obj is int i && i > 10)
{
Console.WriteLine("Large integer");
}
// Or using when in switch
string result = obj switch
{
int x when x > 0 => "Positive int",
int x => "Non-positive int",
null => "Null",
_ => "Other"
};

Handling different JSON token types: When parsing JSON with System.Text.Json, you can use type pattern to handle JsonValueKind.Number, JsonValueKind.String, etc.

Example: JsonDocument returns JsonElement; you can check ValueKind with type pattern.