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?????;
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.
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.
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.
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.
Is something like this what you're looking for?
TestClass.testColor = (Color)Enum.Parse(typeof(Color), collectionofstrings[23]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With