Created
May 13, 2015 04:09
-
-
Save Porges/d9879ad5ffb9d9aee0a2 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
[StructLayout(LayoutKind.Explicit)] | |
public struct IntOrDouble | |
{ | |
private enum Type : byte | |
{ | |
Integral, | |
Floating | |
} | |
[FieldOffset(0)] | |
private readonly Type _type; | |
[FieldOffset(1)] | |
private readonly int _intValue; | |
[FieldOffset(1)] | |
private readonly double _doubleValue; | |
public IntOrDouble(int value) : this() | |
{ | |
_type = Type.Integral; | |
_intValue = value; | |
} | |
public IntOrDouble(double value) : this() | |
{ | |
_type = Type.Floating; | |
_doubleValue = value; | |
} | |
public void With(Action<int> intAction, Action<double> doubleAction) | |
{ | |
switch (_type) | |
{ | |
case Type.Integral: | |
intAction(_intValue); | |
break; | |
case Type.Floating: | |
doubleAction(_doubleValue); | |
break; | |
default: | |
throw new Exception(); | |
} | |
} | |
public T Match<T>(Func<int, T> intFunc, Func<double, T> doubleFunc) | |
{ | |
switch (_type) | |
{ | |
case Type.Integral: | |
return intFunc(_intValue); | |
case Type.Floating: | |
return doubleFunc(_doubleValue); | |
default: | |
throw new Exception(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment