tags:

views:

341

answers:

4

Say I have an enum

    public enum Colours
    {
        Red,
        Blue
    }

The only way i can see of parsing them is doing something like

string colour = "Green";
var col = (Colours)Enum.Parse(typeOf(Colours),colour);

This will throw a system.argumentexception because "Green" is not a member of the Colours enum.

Now I really hate wrapping code in try/catch's, is there no neater way to do this that doesnt involve me iterating through each Colours enum, and doing a string comparison against colour ?

+5  A: 

Use Enum.IsDefined() first to save yourself from wrapping in a try catch. It'll return a boolean value of whether or not the input is a valid member of that enum.

statenjason
+3  A: 

No, there's no "no-throw" method for this (a la TryParse that some other classes have).

However, you could easily write your own so as to encapsulate the try-catch logic (or the IsDefined check) in one helper method so it doesn't pollute your app code:

public static object TryParse(Type enumType, string value, out bool success)
{
  success = Enum.IsDefined(enumType, value);
  if (success)
  {
    return Enum.Parse(enumType, value);
  }
  return null;
}
itowlson
+1  A: 

You could do something like this:

Colours TryParseColours(string name, Colours defaultValue)
{
    try
    {
        return (Colours)Enum.Parse(typeof(Colours), name);
    }
    catch (ArgumentException)
    {
    }

    // if the parsing fails, return defaultValue
    return defaultValue;
}
Zach Johnson
+3  A: 

I believe that 4.0 has Enum.TryParse

Otherwise use an extension method:

public static bool TryParse<T>(this Enum theEnum, string valueToParse, out T returnValue)
{
    returnValue = default(T);
    int intEnumValue;
    if (Int32.TryParse(valueToParse, out intEnumValue))
    {
        if (Enum.IsDefined(typeof(T), intEnumValue))
        {
            returnValue = (T)(object)intEnumValue;
            return true;
        }
    }
    return false;
}
Sky Sanders