wajira000 wajira000 - 2 months ago 7
ASP.NET (C#) Question

Pass enum to method

I'm new to C#. Recently I got a problem on a project. I need to generate dropdown using enum list. I found a good working sample.
But that sample use only one enum my requirement is use this code for any enum. I cant figure it out. My code is

public List<SelectListItem> GetSelectListItems()
{
var selectList = new List<SelectListItem>();

var enumValues = Enum.GetValues(typeof(Industry)) as Industry[];
if (enumValues == null)
return null;

foreach (var enumValue in enumValues)
{
// Create a new SelectListItem element and set its
// Value and Text to the enum value and description.
selectList.Add(new SelectListItem
{
Value = enumValue.ToString(),
// GetIndustryName just returns the Display.Name value
// of the enum - check out the next chapter for the code of this function.
Text = GetEnumDisplayName(enumValue)
});
}

return selectList;
}


I need to pass any enum to this method. Any help is appreciate.

Answer

Maybe this:

public List<SelectListItem> GetSelectListItems<TEnum>() where TEnum : struct
{
  if (!typeof(TEnum).IsEnum)
    throw new ArgumentException("Type parameter must be an enum", nameof(TEnum));

  var selectList = new List<SelectListItem>();

  var enumValues = Enum.GetValues(typeof(TEnum)) as TEnum[];
  // ...

This makes your method generic. To call it, use e.g.:

GetSelectListItems<Industry>()

By the way, I think you could replace the as TEnum[] with a "hard" cast to TEnum[] and skip that null check:

  var enumValues = (TEnum[])Enum.GetValues(typeof(TEnum));