converting string in enum !!!

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
 
B

Ben Voigt [C++ MVP]

Harald said:
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???
System.Enum.TryParse


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
 

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