Similar to Cast int to enum in C# but my enum is a Generic Type parameter. What is the best way to handle this?
Example:
private T ConvertEnum<T>(int i) where T : struct, IConvertible { return (T)i; }
Generates compiler error Cannot convert type 'int' to 'T'
Full code is as follows, where value can contain the int, or null.
private int? TryParseInt(string value) { var i = 0; if (!int.TryParse(value, out i)) { return null; } return i; } private T? TryParseEnum<T>(string value) where T : struct, IConvertible { var i = TryParseInt(value); if (!i.HasValue) { return null; } return (T)i.Value; }
You can explicitly type cast an int to a particular enum type, as shown below.
Enum's in . Net are integral types and therefore any valid integral value can be cast to an Enum type. This is still possible even when the value being cast is outside of the values defined for the given enumeration!
Just cast it: MyEnum e = (MyEnum)3; Check if it's in range using Enum.
The simplest way I have found is to force the compiler's hand by adding a cast to object
.
return (T)(object)i.Value;
You should be able to use Enum.Parse
for this:
return (T)Enum.Parse(typeof(T), i.Value.ToString(), true);
This article talks about parsing generic enums for extenstion methods:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With