Last active
December 18, 2015 17:49
-
-
Save kmorcinek/5821522 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
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