CKTIS / C#
pattern matching: practical reference
pattern matching: practical reference: C# patterns test type, value, and structure and can bind variables.
Version: C# language and .NET 10 reference runtime
Syntax
// patternsC# patterns test type, value, and structure and can bind variables.
Use a switch expression for exhaustive mapping of cases.
Arm order matters; an earlier broad pattern can shadow later arms.
null does not match an ordinary type pattern; a missing case can throw.
The complete program actually uses pattern matching; its exact expected stdout is positive:7.
Examples
using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;
object value = 7; var text = value switch { int number and > 0 => $"positive:{number}", null => "null", _ => "other" }; Console.WriteLine(text);
Result
positive:7
The complete program actually uses `pattern matching`; its exact expected stdout is `positive:7`.