Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cast a generic enum to int?

Tags:

c#

enums

I have a small method that looks like this:

public void SetOptions<T>() where T : Enum {     int i = 0;     foreach (T obj in Enum.GetValues(typeof(T)))     {         if (i == 0)             DefaultOption = new ListItem(obj.Description(), obj.ToString());         i++;         DropDownList.Items.Add(new ListItem(obj.Description(), obj.ToString()));     } } 

Basically, I populate a dropdown list from an enum. Description() is actually an extension method for enums, so T is definitely an enum.

However, I want to cast obj just as you would any enum to its index like this (int)obj, but I get an error saying I can't convert T to int. Is there a way to do this?

like image 498
dotnetnoob Avatar asked Jun 06 '13 11:06

dotnetnoob


2 Answers

You could also cast your value to object first and then to int.

C# 7.3 and above

With the Enum generic constraint.

public static int EnumToInt<TValue>(this TValue value) where TValue : Enum     => (int)(object)value; 

Below C# 7.3

Without the Enum generic constraint.

public static int EnumToInt<TValue>(this TValue value)  where TValue : struct, IConvertible {     if(!typeof(TValue).IsEnum)     {         throw new ArgumentException(nameof(value));     }      return (int)(object)value; } 

If your enum inherits from other types for example from byte the cast to int will throw an InvalidCastException.

You could either check if the base type of the enum is an integer.

public static int EnumToInt<TValue>(this TValue value) where TValue : Enum {     if (!typeof(int).IsAssignableFrom(Enum.GetUnderlyingType(typeof(TValue))))         throw new ArgumentException(nameof(TValue));      return (int)(object)value; } 

Or you if you use Convert.ToInt32 it will use the IConvertible interface of int32 to convert the incompatible types.

public static int EnumToInt<TValue>(this TValue value) where TValue : Enum     => Convert.ToInt32(value); 

Just be aware the converting uint to int and signed/unsigned pairs can cause unintended behavior. (Boxing to IConvertible and the converting is less performant than just unboxing.)


I recommend creating a method for each enum base type to ensure the correct result is returned.

like image 115
NtFreX Avatar answered Sep 19 '22 23:09

NtFreX


try this,

public void SetOptions<T>() {     Type genericType = typeof(T);     if (genericType.IsEnum)     {         foreach (T obj in Enum.GetValues(genericType))         {             Enum test = Enum.Parse(typeof(T), obj.ToString()) as Enum;             int x = Convert.ToInt32(test); // x is the integer value of enum                         ..........                         ..........         }     } } 
like image 23
petchirajan Avatar answered Sep 19 '22 23:09

petchirajan