Enum.Parse(), surely a neater way?

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


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;
}

Just to expand on Sky's link to the .Net 4 Enum.TryParse<>, viz

Enum.TryParse<TEnum>(
    string value,
    [bool ignoreCase,]
    out TEnum result
)

This can be used as follows:

    enum Colour
    {
        Red,
        Blue
    }

    private void ParseColours()
    {
        Colour aColour;

        // IMO using the actual enum type is intuitive, but Resharper gives 
        // "Access to a static member of a type via a derived type"
        if (Colour.TryParse("RED", true, out aColour))
        {
           // ... success
        }

        // OR, the compiler can infer the type from the out
        if (Enum.TryParse("Red", out aColour))
        {
           // ... success
        }

        // OR explicit type specification
        // (Resharper: Type argument specification is redundant)
        if (Enum.TryParse<Colour>("Red", out aColour))
        {
          // ... success
        }
    }

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;
}

If I'm parsing a "trusted" enum, then I use Enum.Parse().
By "trusted" I mean, I know it will ALWAYS be a valid enum without ever erroring... ever!

But there are times when "you never know what you're gonna get", and for those times, you need to use a nullable return value. Since .net doesn't offer this baked in, you can roll your own. Here's my recipe:

public static TEnum? ParseEnum<TEnum>(string sEnumValue) where TEnum : struct
{
    TEnum eTemp;
    TEnum? eReturn = null;
    if (Enum.TryParse<TEnum>(sEnumValue, out eTemp) == true)
        eReturn = eTemp;
    return eReturn;
}

To use this method, call it like so:

eColor? SelectedColor = ParseEnum<eColor>("Red");

Just add this method to a class you use to store your other commonly used utility functions.