Skip to content

Instantly share code, notes, and snippets.

@jonpryor
Created August 29, 2018 00:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonpryor/5dd1ce25ebe6c5d14ec8a17e7c4e9622 to your computer and use it in GitHub Desktop.
Save jonpryor/5dd1ce25ebe6c5d14ec8a17e7c4e9622 to your computer and use it in GitHub Desktop.
// 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