tags:

views:

463

answers:

4

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?????;
+5  A: 

Is something like this what you're looking for?

TestClass.testColor = (Color)Enum.Parse(typeof(Color), collectionofstrings[23]);
Dmitry Brant
Cannot implicitly convert type Object to Color(the enum).What can I do in this case?
Sergio Tapia
+4  A: 

Try:

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

See documentation about Enum

Sander Rijken
It says I can't convert from Object to Color. Any help?
Sergio Tapia
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
A: 

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
A: 

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