Skip to content

Instantly share code, notes, and snippets.

@davidelettieri
Created March 25, 2020 22:08
Show Gist options
  • Save davidelettieri/62ff5eda957f8e5bc35c62e2158ebb94 to your computer and use it in GitHub Desktop.
Save davidelettieri/62ff5eda957f8e5bc35c62e2158ebb94 to your computer and use it in GitHub Desktop.
public class Union<TOne, TOther>
{
private readonly TOne _toneValue;
private readonly TOther _totherValue;
private readonly UnionType _type;
public Union(TOne value)
{
_toneValue = value;
_type = UnionType.TOne;
}
public Union(TOther value)
{
_totherValue = value;
_type = UnionType.TOther;
}
public void Switch(Action<TOne> actionTOne, Action<TOther> actionTOther)
{
switch (_type)
{
case UnionType.TOne:
actionTOne(_toneValue);
break;
case UnionType.TOther:
actionTOther(_totherValue);
break;
}
}
public TResult Match<TResult>(Func<TOne, TResult> funcTOne, Func<TOther, TResult> funcTOther)
{
switch (_type)
{
case UnionType.TOne:
return funcTOne(_toneValue);
case UnionType.TOther:
return funcTOther(_totherValue);
}
throw new InvalidOperationException();
}
enum UnionType
{
TOne,
TOther
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment