Skip to content

Instantly share code, notes, and snippets.

@rgarner
Forked from mythz/csharp7-switch.cs
Created August 26, 2016 21:29
Show Gist options
  • Save rgarner/1206e3a9b29139a429234fb16dfcb6a2 to your computer and use it in GitHub Desktop.
Save rgarner/1206e3a9b29139a429234fb16dfcb6a2 to your computer and use it in GitHub Desktop.
Proposed pattern matching in C#
// From: https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/
switch(shape)
{
case Circle c:
WriteLine($"circle with radius {c.Radius}");
break;
case Rectangle s when (s.Length == s.Height):
WriteLine($"{s.Length} x {s.Height} square");
break;
case Rectangle r:
WriteLine($"{r.Length} x {r.Height} rectangle");
break;
default:
WriteLine("<unknown shape>");
break;
case null:
throw new ArgumentNullException(nameof(shape));
}
match (shape)
{
Circle c => WriteLine($"circle with radius {c.Radius}");
Rectangle s when (s.Length == s.Height) { //statement block example
WriteLine($"{s.Length} x {s.Height} square");
}
Rectangle r => WriteLine($"{r.Length} x {r.Height} rectangle");
default => WriteLine("<unknown shape>");
null => throw new ArgumentNullException(nameof(shape));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment