Cannot convert string to Enum type I created

Viewed 25664

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?????;
4 Answers

Is something like this what you're looking for?

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

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"
}

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);

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());
Related