c# - Enum item mapped to another value -


i have enum:

enum myenum{     aaaval1,     aaaval2,     aaaval3, }   

i need have abbreviated version of 'myenum' maps every item 'myenum' different values. current approach method translates every item:

string translate(myenum myenum) {     string result = "";     switch ((int)myenum)     {         0:   result = "abc";         1:   result = "dft";         default: result = "fsdfds"     }     return result; } 

the problem approach every time programmer changes myenum should change translate method.

this not way of programming.

so..

is there more elegant solution problem?

thank :-)

four options:

  • decorate enum values attributes, e.g.

    enum myenum {     [description("abc")]     aaaval1,     [description("dft")]     aaaval2,     aaaval3, }  

    then can create mapping (like dictionary solution below) via reflection.

  • keep switch statement switch on enum value instead of number better readability:

    switch (myenum) {     case myenum.aaaval1: return "abc";     case myenum.aaaval2: return "dft";     default:             return "fsdfds"; } 
  • create dictionary<myenum, string>:

    private static dictionary<myenum, string> enumdescriptions =      new dictionary<myenum, string> {     { myenum.aaaval1, "abc" },     { myenum.aaaval2, "dft" },         }; 

    you'd need handle defaulting in method, of course.

  • use resource file, entry each string representation. better if you're trying translate in way might need different translations different cultures.


Comments

Popular posts from this blog

java - How to Configure JAXRS and Spring With Annotations -

visual studio - TFS will not accept changes I've made to a Java project -

php - Create image in codeigniter on the fly -