Created
January 25, 2015 22:14
-
-
Save siroky/0d6c3d1c96692c876f19 to your computer and use it in GitHub Desktop.
Type Match in C# using FuncSharp
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
class Parent { } | |
class A : Parent { public string A { get; private set; } } | |
class B : Parent { public string B { get; private set; } } | |
class C : Parent { public string C { get; private set; } } | |
public class Test | |
{ | |
public string TestWithoutFuncSharp(Parent p) | |
{ | |
var a = p as A; | |
if (a != null) | |
{ | |
return a.A; | |
} | |
var b = p as B; | |
if (b != null) | |
{ | |
return b.B; | |
} | |
var c = p as C; | |
if (c != null) | |
{ | |
return c.C; | |
} | |
throw new ArgumentException(); // or return "otherwise". | |
} | |
public string Test(Parent p) | |
{ | |
return p.AsUnion<A, B, C>().Match( | |
a => a.A, | |
b => b.B, | |
c => c.C | |
); | |
} | |
public string SafeTest(object x) | |
{ | |
return x.AsSafeUnion<A, B, C>().Match( | |
a => a.A, | |
b => b.B, | |
c => c.C, | |
_ => "otherwise" | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment