18

I have an enum:

public enum Color
{
    Red,
    Blue,
    Green,
}

Now if I read those colors as literal strings from an XML file, how can I convert it to the enum type Color.

class TestClass
{
    public Color testColor = Color.Red;
}

Now when setting that attribute by using a literal string like so, I get a very harsh warning from the compiler. :D Can't convert from string to Color.

Any help?

TestClass.testColor = collectionofstrings[23].ConvertToColor?????;
Sergio Tapia
  • 40,006
  • 76
  • 183
  • 254

4 Answers4

38

Is something like this what you're looking for?

TestClass.testColor = (Color)Enum.Parse(typeof(Color), collectionofstrings[23]);
Dmitry Brant
  • 7,612
  • 2
  • 29
  • 47
8

Try:

TestClass.testColor = (Color)Enum.Parse(typeof(Color), collectionofstrings[23]);

See documentation about Enum

Edit: in .NET 4.0 you can use a more type-safe method (and also one that doesn't throw exceptions when parsing fails):

Color myColor;
if (Enum.TryParse(collectionofstring[23], out myColor))
{
    // Do stuff with "myColor"
}
Sander Rijken
  • 21,376
  • 3
  • 61
  • 85
  • It says I can't convert from Object to Color. Any help? – Sergio Tapia Jan 04 '10 at 00:20
  • 2
    Then you probably forgot the cast to Color in front of the call to Parse. This is for sure the method to go from string to enum. – Matt Greer Jan 04 '10 at 00:24
  • @MattGreer this is a better way of doing it if you *care* when the parse "fails". It's true it won't throw an exception if it can't actually be parsed, but instead it will return whatever the `0` entry in the enum is and you'd have no clue it actually failed. – Don Cheadle Jan 14 '16 at 22:35
0

You need to use Enum.Parse to convert your string to the correct Color enum value:

TestClass.testColor = (Color)Enum.Parse(typeof(Color), collectionofstrings[23], true);
Rob Levine
  • 40,328
  • 13
  • 85
  • 111
0

As everyone else has said:

TestClass.testColor = (Color) Enum.Parse(typeof(Color), collectionofstrings[23]);

If you're having an issue because the collectionofstrings is a collection of objects, then try this:

TestClass.testColor = (Color) Enum.Parse(
    typeof(Color), 
    collectionofstrings[23].ToString());
cdmckay
  • 31,832
  • 25
  • 83
  • 114