How to pass a string to a given Enum

how to do string enumeration?

I have the code below, it gives me an error when I try to assign the line levelEnum, where levelEnum is an enum.

foreach (CustomProperty prop in requirementTemplate.AttributesCustomList) { if (prop.Name == property) { return (CRF_DB.CRF_Requirement.LevelEnum) (prop.Value.ToString()); } } 

Is there a way to put an Enum select element by assigning a value to it?

hope this is clear enough

+4
source share
3 answers

Try to execute

 return (CRF_DB.CRF_Requirement.LevelEnum)Enum.Parse( typeof(CRF_DB.CRF_Requirement.LevelEnum), prop.Value.ToString()); 
+6
source

To avoid an exception, you can check if this value exists in this enumeration by calling IsDefined . TryParse would be the best solution if you are using .NET 4.0.

 foreach (CustomProperty prop in requirementTemplate.AttributesCustomList) { if (prop.Name == property && Enum.IsDefined(typeof(LevelEnum), prop.Value)) { return (LevelEnum)Enum.Parse(typeof(LevelEnum), prop.Value.ToString()); } } 
0
source

All Articles