Created
May 17, 2016 02:01
-
-
Save waf/273228a80e0f973d804f55497335c292 to your computer and use it in GitHub Desktop.
Pattern matching in C#. This is terrible. Don't actually do this.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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