Skip to content

Instantly share code, notes, and snippets.

@jonpryor jonpryor/st.cs
Created Aug 29, 2018

Embed
What would you like to do?
// switch on type?
using System;
class App {
public static void Main ()
{
sbyte v;
if (TryConvert (42.0, out v)) {
Console.WriteLine ($"v={v}");
}
}
internal static bool TryConvertSByte (double value, out sbyte outValue)
{
if (value < sbyte.MinValue || value > sbyte.MaxValue)
{
outValue = 0;
return false;
}
outValue = (sbyte) Math.Round(value);
return true;
}
internal static bool TryConvert<T>(double value, out T outValue)
where T : struct
{
outValue = default (T);
switch (typeof (T)) {
case Type sbyteType when sbyteType == typeof (sbyte):
sbyte v;
if (TryConvertSByte (value, out v)) {
outValue = (T) (object) v;
return true;
}
break;
default:
break;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.