Converting string to enum member!!!

H

Harald

Hi, sorry if this is not the best group for this...

In C# I have string values that correspond to enum member names. I need a
conversion from the string value to the corresponding enum value - if
possible without a big switch comparing the string with all their enum
string literal representations. Thougth, there must be a trick with
reflection or so. Anyone an idea???

Sample (pseudo code):

enum color { red, green blue };
string myCol = "red";

try {
color Receiver = (color)myCol; // this is erroneous because the cast is
not possible, but thats what I need :)
}
catch {
....
}

Thx for all replies!
-hd
 
H

Hilton

Color color;

switch (myCol)
{
case "red": color = Color.Red; break;
case "black" : color = Color.Black; break;
etc...
}

Rene's solution breaks when you obfuscate it.

Hilton
 
J

Jon Skeet [C# MVP]

Color color;

switch (myCol)
{
case "red": color = Color.Red; break;
case "black" : color = Color.Black; break;
etc...

}

Rene's solution breaks when you obfuscate it.

Your solution breaks if you ever change a name and forget to change
the switch statement, or mistype the name within the switch statement.

I'd expect any decent obfuscator to allow you to specify what should
be renamed, so you should be able to exclude enums (all or specific
ones).

Rene's solution is the standard way of doing this, and the one I'd
recommend.

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top