converting string in enum !!!

  • Thread starter Thread starter Harald
  • Start date Start date
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
 
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
 
Back
Top