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);}With when clause
Section titled “With when clause”object obj = 42;if (obj is int i && i > 10){ Console.WriteLine("Large integer");}// Or using when in switchstring result = obj switch{ int x when x > 0 => "Positive int", int x => "Non-positive int", null => "Null", _ => "Other"};Real-world usage example
Section titled “Real-world usage example”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.