Skip to content

Instantly share code, notes, and snippets.

@Porges
Created May 13, 2015 04:09
Show Gist options
  • Save Porges/d9879ad5ffb9d9aee0a2 to your computer and use it in GitHub Desktop.
Save Porges/d9879ad5ffb9d9aee0a2 to your computer and use it in GitHub Desktop.
[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