// Main.cs, an example of usage using System; using Parser; ... static void Main() { Parsed x = new Ok(4); // Is there any way to avoid having to write "Parsed.Fn"? // I'm trying to use some pattern-matching-esque idiom. Console.WriteLine(x.Match(new Parsed.Fn { Ok = z => z.Value, Error = z => 9 })); } // Result.cs: using System; namespace Parser { public abstract class Parsed { // A Parsed.Fn, as used by Match, performs an action depending on the type. public class Fn { public Func, T> Ok { get; set; } public Func, T> Error { get; set; } } public List Context { get; private set; } // You can see that Match takes a Fn and in the children // calls the right method. abstract public T Match(Fn matcher); } public class Ok : Parsed { public A Value { get; private set; } public override T Match(Fn matcher) { return matcher.Ok(this); } public Ok(A value) { this.Value = value; } } public class Error : Parsed { public string Message { get; private set; } public Error(string message) : this(message, new List()) { } public Error(string message, List context) { Message = message; Context = context; } public override T Match(Fn matcher) { return matcher.Error(this); } } }