Skip to content

Instantly share code, notes, and snippets.

@mythz
Last active August 26, 2016 21:29
Show Gist options
  • Save mythz/422dcac0c7cc6feea00ed48ffec3964f to your computer and use it in GitHub Desktop.
Save mythz/422dcac0c7cc6feea00ed48ffec3964f 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