Enum.Parse(), surely a neater way?

C#asp.netEnums

C# Problem Overview


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 doesn't involve me iterating through each Colours enum, and doing a string comparison against colour?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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

Solution 3 - C#

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

Solution 4 - C#

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

Solution 5 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmaxpView Question on Stackoverflow
Solution 1 - C#statenjasonView Answer on Stackoverflow
Solution 2 - C#Sky SandersView Answer on Stackoverflow
Solution 3 - C#StuartLCView Answer on Stackoverflow
Solution 4 - C#itowlsonView Answer on Stackoverflow
Solution 5 - C#MikeTeeVeeView Answer on Stackoverflow