Reputation: 10364
I have a generic method which will return a select list populated from an enum.
public static IEnumerable<SelectListItem> GetGenericEnumSelectList<T>()
{
return (Enum.GetValues(typeof(T)).Cast<int>().Select(e => new SelectListItem() { Text = EnumExtensions.GetEnumDescription((ProductsEnum)e) , Value = e.ToString() })).ToList();
}
I have put a call to a static method I also have called GetEnumDescription
, this expects an Enum. How can I pass in the current type rather than hard coding the type as I have done. So that if T
is a different type of enum, it will be generic.
Something like:
public static IEnumerable<SelectListItem> GetGenericEnumSelectList<T>()
{
return (Enum.GetValues(typeof(T)).Cast<int>().Select(e => new SelectListItem() { Text = EnumExtensions.GetEnumDescription((typeof(T))e) , Value = e.ToString() })).ToList();
}
EDIT
Signature of GetEnumDescription
is
public static string GetEnumDescription(Enum value)
{
///
}
Upvotes: 0
Views: 104
Reputation: 37000
Unfortunately there´s no generic constraint for enums - at least not before C#7.3. So the following isn´t possible:
void SoSomething<T>(T myEnum) where T: Enum { }
You could add another constraint as mentioned here:
void SoSomething<T>(T myEnum) where T: struct, IConvertible{ }
However that won´t help you much.
However in your case there´s no need to cast at all, as your methods parameter is Enum
. So you can simply cast e
to Enum
:
return (Enum.GetValues(typeof(T)).Cast<Enum>().Select(e => new SelectListItem {
Text = EnumExtensions.GetEnumDescription(e),
Value = Convert.ToInt32(e).ToString()
})).ToList();
Bw aware on the cast to Enum
. Otherwise you get the following error:
Cannot convert type
int
toSystem.Enum
Upvotes: 3