using System; using System.Collections.Generic; public class Test { public static void Main() { var l = new List> { new Union3(DateTime.Now), new Union3(42), new Union3("test"), new Union3("one more test") }; foreach (Union3 union in l) { string value = union.Match( str => str, dt => dt.ToString("yyyy-MM-dd"), i => i.ToString()); Console.WriteLine("Matched union with value '{0}'", value); } } } public sealed class Union3 { readonly A Item1; readonly B Item2; readonly C Item3; int tag; public Union3(A item) { Item1 = item; tag = 0; } public Union3(B item) { Item2 = item; tag = 1; } public Union3(C item) { Item3 = item; tag = 2; } public T Match(Func f, Func g, Func h) { switch (tag) { case 0: return f(Item1); case 1: return g(Item2); case 2: return h(Item3); default: throw new Exception("Unrecognized tag value: " + tag); } } }