Pattern matching is used for:
- testing expression to check if some value have certain characteristics
- safer compare because ‘==’ and ‘!=’ can be overloaded
Examples:
a is int number
sequence is IList<T> list
switch statement:
command switch { Operation.SystemTest => RunDiagnostics(), Operation.Start => StartSystem(), Operation.Stop => StopSystem(), Operation.Reset => ResetToReady(), _ => throw new ArgumentException("Invalid enum value for command", nameof(command)), };
switch with ranges:
tempInFahrenheit switch { (> 32) and (< 212) => "liquid", < 32 => "solid", > 212 => "gas", 32 => "solid/liquid transition", 212 => "liquid / gas transition", };
collection pattern matching:
array is [1,1,2,3,5,8, ..]
Further read:
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching
One Reply to “Pattern matching”