0

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.

1
  • can you please add the link to the duplicate answer Commented Mar 6, 2017 at 8:48

1 Answer 1

2

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)); 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much. Now it's working fine. You saved me.
How to use as TEnum[] with hard TEnum?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.