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?????; 
0

4 Answers 4

39

Is something like this what you're looking for?

TestClass.testColor = (Color)Enum.Parse(typeof(Color), collectionofstrings[23]); 
Sign up to request clarification or add additional context in comments.

2 Comments

Cannot implicitly convert type Object to Color(the enum). What can I do in this case?
@Sergio Then you missed the explicit cast (Color)
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" } 

3 Comments

It says I can't convert from Object to Color. Any help?
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.
@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.
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); 

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.