C# Treat an enum as an array -
in project have enum
in store music genres values looks :
enum genres { rock,pop,disco,sport,talk,metal,hard_rock,electro,classic_rock}
now in code want foreach
loop work based on music genre.something this:
foreach(genres genre in enum.getvalues(typeof(genres))) { switch(genre) { case genres.disco: //do break; case genres.rock: //do break; ..... ....... } }
what want treat enum
in switch
case array.something this:
foreach(genres genre in enum.getvalues(typeof(genres))) { switch(genre) { case genres[0]: //do break; case genres[1]: //do break; ..... ....... } }
is possible? in advance.
edit
i have listbox in want populate genreitems. every listboxitem want have diffent name ass pass them in. make switch in order check genre , case rock example set listboxitem rock , add in listbox.
i don't think it's possible unless tweaks... example, use static array store values:
public static readonly genres[] allgenres = enum.getvalues(typeof(genres)).cast<genres>().toarray(); // sample: public void test() { var first = allgenres [0]; }
edit
now understand need. want list bind control. think might want try use attribute enum if think need description, , write generic method retrieve enum items , wrap object, like:
public enum genres { [description("rock!!!")] rock, pop, disco, sport, talk, metal, hard_rock, electro, [description("classic rock")] classic_rock } public class enumitem { string name { get; set; } string description { get; set; } enum enumvalue {get;set;} public static ienumerable<enumitem> getvalue(type t) { // implementation using reflection/expression } } // can use retrieved list/whatever binding or so...
you may further tweak meet needs (for example, using type constraint make better) - , more important, become generic class serve enum types...
Comments
Post a Comment