c# - How can I cast <T> as Enum when using EnumToList<T> -


i have simple class selectitemoption used generically in dropdowns, lists, etc.

public class selectitemoption {     public string title { get; set; }     public string id { get; set; }     public string description { get; set; } } 

i want create method populates list<selectitemoption> values enum. getdisplayname() , getdisplaydescription() info attributes.

i robbed code another answer enum values enumerable.

    public static ienumerable<t> enumtolist<t>()         t : struct     {         return enum.getvalues(typeof(t)).cast<t>();     } 

i attempting put this:

    public static list<selectitemoption> enumasselectitemoptions<t>()         t : struct     {         var optionslist = new list<selectitemoption>();         foreach (var option in enumtolist<t>())   //** headache here **         {             optionslist.add(new selectitemoption()             {                 title = option.getdisplayname(),                 id = option.tostring(),                 description = option.getdisplaydescription()             });         }         return optionslist;     } 

the problem occurs when try iterate enumtolist.

no matter try, can't seem option variable act enum.

i've tried...

if use foreach (enum option in enumtolist<t>()) "cannot convert type t system.enum".

but if use foreach (var option in enumtolist<t>()) extension methods aren't recognised.

if try cast option enum after foreach statement "cannot implicitly convert type t system.enum".

aaaaggggghhhhh!

you can't constrain enum option can struct. however, try write enumasselectitemoptions method this:

public static list<selectitemoption> enumasselectitemoptions<t>()     t : struct {     var optionslist = new list<selectitemoption>();     foreach (var option in enumtolist<t>())   //** headache here **     {         optionslist.add(new selectitemoption()         {             title = option enum                 ? (option enum).getdisplayname()                 : option.tostring(),             id = option.tostring(),             description = option enum                 ? (option enum).getdisplaydescription()                 : option.tostring(),         });     }     return optionslist; } 

Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -