Created
March 25, 2020 22:08
-
-
Save davidelettieri/62ff5eda957f8e5bc35c62e2158ebb94 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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