4

how to cast string enum ?

i have the code below , it gives me error when i try to assign string to levelEnum, where levelEnum is an Enumeration..

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 select Enum item by assigning value to it ?

hope it is clear enough

1
  • 1
    What's the type of the value returned by prop.Value? Commented Aug 16, 2011 at 19:46

3 Answers 3

6

Try the following

return (CRF_DB.CRF_Requirement.LevelEnum)Enum.Parse(
  typeof(CRF_DB.CRF_Requirement.LevelEnum), 
  prop.Value.ToString());
Sign up to request clarification or add additional context in comments.

Comments

2

Look at Enum.TryParse

http://msdn.microsoft.com/en-us/library/dd783499.aspx

Comments

0

In order to avoid an exception you can check if the value exists within that enumeration by calling IsDefined. The TryParse method would be the optimal solution if you're 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());
    }
}

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.