Skip to content

Instantly share code, notes, and snippets.

@afifmohammed
Created December 16, 2019 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afifmohammed/429af9ceac8b4078c4664a8cfb921563 to your computer and use it in GitHub Desktop.
Save afifmohammed/429af9ceac8b4078c4664a8cfb921563 to your computer and use it in GitHub Desktop.
Discriminated unions in C#
using System;
namespace Juliet
{
class Program
{
static void Main(string[] args)
{
Union3<int, char, string>[] unions = new Union3<int,char,string>[]
{
new Union3<int, char, string>(5),
new Union3<int, char, string>('x'),
new Union3<int, char, string>("Juliet")
};
foreach (Union3<int, char, string> union in unions)
{
string value = union.Match(
num => num.ToString(),
character => new string(new char[] { character }),
word => word);
Console.WriteLine("Matched union with value '{0}'", value);
}
Console.ReadLine();
}
}
public sealed class Union3<A, B, C>
{
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<T>(Func<A, T> f, Func<B, T> g, Func<C, T> 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);
}
}
}
}
@afifmohammed
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment