Discriminative unions and pattern matching can be modeled in C #, although type definitions are a bit detailed (see How can I duplicate a F # type union in C # for some ideas). Here's the approach I advocated in this matter: type F # type T = ACase of A | BCase of B | CCase of C type T = ACase of A | BCase of B | CCase of C type T = ACase of A | BCase of B | CCase of C can be represented by an abstract C # class with some static helper methods.
public abstract class T { public abstract X Match<X>(Func<A,X> aCase, Func<B,X> bCase, Func<C,X> cCase); private class ACase : T { private A a; public ACase(A a) { this.a = a; } public override X Match<X>(Func<A,X> aCase, Func<B,X> bCase, Func<C,X> cCase) { return aCase(a); } } private class BCase : T { private B b; public BCase(B b) { this.b = b; } public override X Match<X>(Func<A,X> aCase, Func<B,X> bCase, Func<C,X> cCase) { return bCase(b); } } private class CCase : T { private C c; public CCase(C c) { this.c = c; } public override X Match<X>(Func<A,X> aCase, Func<B,X> bCase, Func<C,X> cCase) { return cCase(c); } } public static T MakeACase(A a) { return new ACase(a); } public static T MakeBCase(B b) { return new BCase(b); } public static T MakeCCase(C c) { return new CCase(c); } }
The match now looks like F #, but without labels. Equivalent to this F # code:
function | A a -> 1 | B b -> 2 | C c -> 3
Is this C # code:
public static int MatchDemo(T t) { return t.Match( a => 1, b => 2, c => 3); }
source share