Skip to content

Instantly share code, notes, and snippets.

@waf
Created May 17, 2016 02:01
Show Gist options
  • Save waf/273228a80e0f973d804f55497335c292 to your computer and use it in GitHub Desktop.
Save waf/273228a80e0f973d804f55497335c292 to your computer and use it in GitHub Desktop.
Pattern matching in C#. This is terrible. Don't actually do this.
namespace PatternMatchTest
{
class Program
{
public static void Main()
{
Animal[] TestCases = {
new Dog(),
new Cat { IsDangerous = true },
new Cat { IsDangerous = false }
};
foreach(var animal in TestCases)
{
string sound = PatternMatchSound(animal);
Console.WriteLine(sound);
}
Console.ReadKey();
}
static string PatternMatchSound(Animal animal)
{
try { throw animal; }
catch(Dog d) { return d.Woof(); }
catch(Cat c) when (c.IsDangerous) { return $"Watch out! {c.Sound()}"; }
catch(Cat c) when (!c.IsDangerous) { return $"Awwwwwww! {c.Sound()}"; }
}
}
class Dog : Animal { public string Woof() => "Woof!"; }
class Cat : Animal {
public bool IsDangerous { get; set; }
public string Sound() => IsDangerous ? "Roar!" : "Meow!";
}
abstract class Animal : Exception { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment