Pattern matching was introduced in C# 7.0.
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; }
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); switch(s) { // perform more specific pattern matching case FileStream writeableFile when s.CanWrite: message = "The stream is a writeable file."; break; case FileStream readOnlyFile: message = "The stream is a read-only file."; break; case MemoryStream ms: message = "The stream is a memory address."; break; // always evaluated last default: message = "The stream is some other type."; break; case null: message = "The stream is null."; break; } ...
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." }; ...