fork download
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. public class Test
  5. {
  6. public static void Main()
  7. {
  8. var l = new List<Union3<string, DateTime, int>> {
  9. new Union3<string, DateTime, int>(DateTime.Now),
  10. new Union3<string, DateTime, int>(42),
  11. new Union3<string, DateTime, int>("test"),
  12. new Union3<string, DateTime, int>("one more test")
  13. };
  14.  
  15. foreach (Union3<string, DateTime, int> union in l)
  16. {
  17. string value = union.Match(
  18. str => str,
  19. dt => dt.ToString("yyyy-MM-dd"),
  20. i => i.ToString());
  21.  
  22. Console.WriteLine("Matched union with value '{0}'", value);
  23. }
  24.  
  25. }
  26. }
  27.  
  28. public sealed class Union3<A, B, C>
  29. {
  30. readonly A Item1;
  31. readonly B Item2;
  32. readonly C Item3;
  33. int tag;
  34.  
  35. public Union3(A item) { Item1 = item; tag = 0; }
  36. public Union3(B item) { Item2 = item; tag = 1; }
  37. public Union3(C item) { Item3 = item; tag = 2; }
  38.  
  39. public T Match<T>(Func<A, T> f, Func<B, T> g, Func<C, T> h)
  40. {
  41. switch (tag)
  42. {
  43. case 0: return f(Item1);
  44. case 1: return g(Item2);
  45. case 2: return h(Item3);
  46. default: throw new Exception("Unrecognized tag value: " + tag);
  47. }
  48. }
  49. }
Success #stdin #stdout 0.05s 33936KB
stdin
Standard input is empty
stdout
Matched union with value '2013-08-19'
Matched union with value '42'
Matched union with value 'test'
Matched union with value 'one more test'