Created
August 29, 2018 00:20
-
-
Save jonpryor/5dd1ce25ebe6c5d14ec8a17e7c4e9622 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
// 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