Skip to content

Instantly share code, notes, and snippets.

@kmorcinek
Last active December 18, 2015 17:49
Show Gist options
  • Save kmorcinek/5821522 to your computer and use it in GitHub Desktop.
Save kmorcinek/5821522 to your computer and use it in GitHub Desktop.
public static class EnumExtensions
{
public static bool TryConvert<TEnum>(int intValue, out TEnum enumValue) where TEnum : struct
{
if (typeof(TEnum).IsEnum == false)
{
throw new ArgumentException("TryConvert works only for Enum types");
}
if (Enum.IsDefined(typeof(TEnum), intValue) == false)
{
enumValue = default(TEnum);
return false;
}
var value = (object)intValue; // casting to object is workaround, cannot do:
enumValue = (TEnum)value; // enumValue = (TEnum)intValue;
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment