Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Juliet

By: a guest on Jul 7th, 2010  |  syntax: C#  |  size: 1.49 KB  |  views: 546  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. using System;
  2.  
  3. namespace Juliet
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             Union3<int, char, string>[] unions = new Union3<int,char,string>[]
  10.                 {
  11.                     new Union3<int, char, string>(5),
  12.                     new Union3<int, char, string>('x'),
  13.                     new Union3<int, char, string>("Juliet")
  14.                 };
  15.  
  16.             foreach (Union3<int, char, string> union in unions)
  17.             {
  18.                 string value = union.Match(
  19.                     num => num.ToString(),
  20.                     character => new string(new char[] { character }),
  21.                     word => word);
  22.                 Console.WriteLine("Matched union with value '{0}'", value);
  23.             }
  24.  
  25.             Console.ReadLine();
  26.         }
  27.     }
  28.  
  29.     public sealed class Union3<A, B, C>
  30.     {
  31.         readonly A Item1;
  32.         readonly B Item2;
  33.         readonly C Item3;
  34.         int tag;
  35.  
  36.         public Union3(A item) { Item1 = item; tag = 0; }
  37.         public Union3(B item) { Item2 = item; tag = 1; }
  38.         public Union3(C item) { Item3 = item; tag = 2; }
  39.  
  40.         public T Match<T>(Func<A, T> f, Func<B, T> g, Func<C, T> h)
  41.         {
  42.             switch (tag)
  43.             {
  44.                 case 0: return f(Item1);
  45.                 case 1: return g(Item2);
  46.                 case 2: return h(Item3);
  47.                 default: throw new Exception("Unrecognized tag value: " + tag);
  48.             }
  49.         }
  50.     }
  51. }