Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast Int to Generic Enum in C#

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; } 
like image 535
csauve Avatar asked Apr 30 '12 16:04

csauve


People also ask

Can you cast an int to a enum?

You can explicitly type cast an int to a particular enum type, as shown below.

Can you cast an enum?

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!

How to convert a number to enum in C#?

Just cast it: MyEnum e = (MyEnum)3; Check if it's in range using Enum.


2 Answers

The simplest way I have found is to force the compiler's hand by adding a cast to object.

return (T)(object)i.Value; 
like image 53
Guvante Avatar answered Oct 06 '22 01:10

Guvante


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:

  • Generic Enum Parsing with Extension Methods
like image 26
James Johnson Avatar answered Oct 06 '22 00:10

James Johnson