Skip to content

Instantly share code, notes, and snippets.

@siroky
Created January 25, 2015 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siroky/0d6c3d1c96692c876f19 to your computer and use it in GitHub Desktop.
Save siroky/0d6c3d1c96692c876f19 to your computer and use it in GitHub Desktop.
Type Match in C# using FuncSharp
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