Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert string to Enum type I created [duplicate]

Tags:

string

c#

enums

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?????;
like image 283
Sergio Tapia Avatar asked Jan 04 '10 00:01

Sergio Tapia


People also ask

How to convert string to enum value?

Use the Enum. IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.

How to convert string to string enum?

To convert string to enum use static method Enum. Parse. Parameters of this method are enum type, the string value and optionally indicator to ignore case.

How to pass string value to enum in c#?

Parse the string value into an Enum Enum. Parse(Type enumType,string value) - This method directly parses the string representation of the name or numeric value of enum member into enumType object. If the string representation of the name is not found, then it will give the exception.

How to Parse enum in c#?

The Parse method in Enum converts the string representation of the name or numeric value of enum constants to an equivalent enumerated object. The following is our enumeration.


1 Answers

Is something like this what you're looking for?

TestClass.testColor = (Color)Enum.Parse(typeof(Color), collectionofstrings[23]);
like image 94
Dmitry Brant Avatar answered Sep 22 '22 22:09

Dmitry Brant