User Tools

Site Tools


Pattern Matching

Pattern matching was introduced in C# 7.0.

Pattern matching with the if statement

The if statement can use the is keyword in combination with declaring a local variable.

object o = "8";
int a = 3;
// Check if the variable 'o' is of type int.
if (o is int b)
    var p = a * b;

Pattern matching with the switch statement

The case values can be patterns.

Match a stream:

using System.IO;
var path = @"C:\Temp\Data";
var message = "";
// Open a file as a writeable stream.
Stream s = File.Open(Path.Combine(path, "data.txt"), FileMode.OpenOrCreate);
    // perform more specific pattern matching
    case FileStream writeableFile when s.CanWrite:
        message = "The stream is a writeable file."; 
    case FileStream readOnlyFile:
        message = "The stream is a read-only file."; 
    case MemoryStream ms:
        message = "The stream is a memory address."; 
    // always evaluated last
        message = "The stream is some other type.";
    case null:
        message = "The stream is null.";

The same code as above using the switch expression:

var message = s switch
    FileStream writeableFile when s.CanWrite => "The stream is a writeable file.",
    FileStream readOnlyFile => "The stream is a read-only file.",
    MemoryStream ms => "The stream is a memory address.",
    null => "The stream is null.",
    _ => "The stream is some other type."
notes/csharp/pattern_matching.txt · Last modified: 2020/09/18 by leszek