115

I want to write a function which can validate a given value (passed as a string) against possible values of an enum. In the case of a match, it should return the enum instance; otherwise, it should return a default value.

The function may not internally use try/catch, which excludes using Enum.Parse, which throws an exception when given an invalid argument.

I'd like to use something along the lines of a TryParse function to implement this:

public static TEnum ToEnum<TEnum>(this string strEnumValue, TEnum defaultValue)
{
   object enumValue;
   if (!TryParse (typeof (TEnum), strEnumValue, out enumValue))
   {
       return defaultValue;
   }
   return (TEnum) enumValue;
}
7
  • 8
    I don't understand this question; you're saying "I want to solve this problem, but I don't want to use any of the methods that would give me a solution." What's the point?
    – Domenic
    Jul 4, 2009 at 16:46
  • 1
    What is your aversion to try/catch solution? If you are trying to avoid Exception becuase they are 'costly', please give yourself a break. In 99% of the cases, Cost to throw/catch cost exception is negligible compared to your main code. Jul 4, 2009 at 17:09
  • 4
    @Domenic: I am just looking for a better solution than what i already know. Would you ever go to a railway enquiry to ask for a route or train that you already know :) . Jul 4, 2009 at 17:38
  • 2
    @Yogi, @Thorarin: try...catch would always be my last choice. About being costly, we never know. what if someone calls my utility method over a list of 100s of items? Jul 4, 2009 at 17:59
  • 2
    @Amby, the cost of simply entering a try/catch block is negligible. The cost of THROWING an exception isn't, but then that's supposed to be exceptional, no? Also, don't say "we never know"... profile the code and find out. Don't waste your time wondering if something is slow, FIND OUT!
    – akmad
    Sep 24, 2009 at 15:09

14 Answers 14

126

Enum.IsDefined will get things done. It may not be as efficient as a TryParse would probably be, but it will work without exception handling.

public static TEnum ToEnum<TEnum>(this string strEnumValue, TEnum defaultValue)
{
    if (!Enum.IsDefined(typeof(TEnum), strEnumValue))
        return defaultValue;

    return (TEnum)Enum.Parse(typeof(TEnum), strEnumValue);
}

Worth noting: a TryParse method was added in .NET 4.0.

6
  • 1
    Best answer I've seen so far... no try/catch, no GetNames :) Jul 4, 2009 at 18:08
  • 13
    Drawbacks to Enum.IsDefined: blogs.msdn.com/brada/archive/2003/11/29/50903.aspx Jul 4, 2009 at 19:51
  • 6
    also there is no ignore case on IsDefined Aug 19, 2010 at 8:33
  • 2
    @Anthony: if you want to support case insensitivity, you would need GetNames. Internally, all these methods (including Parse) use GetHashEntry, which does the actual reflection - once. On the bright side, .NET 4.0 has a TryParse, and it's generic too :)
    – Thorarin
    Aug 19, 2010 at 10:17
  • +1 It saved my day! I am backporting a bunch of code from .NET 4 to .NET 3.5 and you saved me :)
    – daitangio
    May 25, 2011 at 9:02
32

As others have said, you have to implement your own TryParse. Simon Mourier is providing a full implementation which takes care of everything.

If you are using bitfield enums (i.e. flags), you also have to handle a string like "MyEnum.Val1|MyEnum.Val2" which is a combination of two enum values. If you just call Enum.IsDefined with this string, it will return false, even though Enum.Parse handles it correctly.

Update

As mentioned by Lisa and Christian in the comments, Enum.TryParse is now available for C# in .NET4 and up.

MSDN Docs

3
  • Perhaps the least sexy, but I agree this is definitely the best until your code is migrated to .NET 4.
    – Lisa
    Nov 29, 2011 at 6:03
  • 1
    As mentioned below, but not really visible: As of .Net 4 Enum.TryParse is available and works without extra coding. More information is available from MSDN: msdn.microsoft.com/library/vstudio/dd991317%28v=vs.100%29.aspx
    – Christian
    Sep 19, 2013 at 9:36
  • It is worth noting that (as of time of writing for reference source for .NET 4.8) the Microsoft implementation of Enum.TryParse still throws exceptions internally in certain cases - if the string starts with a digit or +/- and the full string cannot be parsed as a number, it will internally catch an exception from Convert.ChangeType, and other exceptions may be thrown internally from a call to ToObject, and then caught within the function leading to a false return code. If a truly exception-free parser is needed, Enum.TryParse does not do this.
    – Steve
    Feb 24, 2022 at 11:21
20

Here is a custom implementation of EnumTryParse. Unlike other common implementations, it also supports enum marked with the Flags attribute.

    /// <summary>
    /// Converts the string representation of an enum to its Enum equivalent value. A return value indicates whether the operation succeeded.
    /// This method does not rely on Enum.Parse and therefore will never raise any first or second chance exception.
    /// </summary>
    /// <param name="type">The enum target type. May not be null.</param>
    /// <param name="input">The input text. May be null.</param>
    /// <param name="value">When this method returns, contains Enum equivalent value to the enum contained in input, if the conversion succeeded.</param>
    /// <returns>
    /// true if s was converted successfully; otherwise, false.
    /// </returns>
    public static bool EnumTryParse(Type type, string input, out object value)
    {
        if (type == null)
            throw new ArgumentNullException("type");

        if (!type.IsEnum)
            throw new ArgumentException(null, "type");

        if (input == null)
        {
            value = Activator.CreateInstance(type);
            return false;
        }

        input = input.Trim();
        if (input.Length == 0)
        {
            value = Activator.CreateInstance(type);
            return false;
        }

        string[] names = Enum.GetNames(type);
        if (names.Length == 0)
        {
            value = Activator.CreateInstance(type);
            return false;
        }

        Type underlyingType = Enum.GetUnderlyingType(type);
        Array values = Enum.GetValues(type);
        // some enums like System.CodeDom.MemberAttributes *are* flags but are not declared with Flags...
        if ((!type.IsDefined(typeof(FlagsAttribute), true)) && (input.IndexOfAny(_enumSeperators) < 0))
            return EnumToObject(type, underlyingType, names, values, input, out value);

        // multi value enum
        string[] tokens = input.Split(_enumSeperators, StringSplitOptions.RemoveEmptyEntries);
        if (tokens.Length == 0)
        {
            value = Activator.CreateInstance(type);
            return false;
        }

        ulong ul = 0;
        foreach (string tok in tokens)
        {
            string token = tok.Trim(); // NOTE: we don't consider empty tokens as errors
            if (token.Length == 0)
                continue;

            object tokenValue;
            if (!EnumToObject(type, underlyingType, names, values, token, out tokenValue))
            {
                value = Activator.CreateInstance(type);
                return false;
            }

            ulong tokenUl;
            switch (Convert.GetTypeCode(tokenValue))
            {
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                case TypeCode.SByte:
                    tokenUl = (ulong)Convert.ToInt64(tokenValue, CultureInfo.InvariantCulture);
                    break;

                //case TypeCode.Byte:
                //case TypeCode.UInt16:
                //case TypeCode.UInt32:
                //case TypeCode.UInt64:
                default:
                    tokenUl = Convert.ToUInt64(tokenValue, CultureInfo.InvariantCulture);
                    break;
            }

            ul |= tokenUl;
        }
        value = Enum.ToObject(type, ul);
        return true;
    }

    private static char[] _enumSeperators = new char[] { ',', ';', '+', '|', ' ' };

    private static object EnumToObject(Type underlyingType, string input)
    {
        if (underlyingType == typeof(int))
        {
            int s;
            if (int.TryParse(input, out s))
                return s;
        }

        if (underlyingType == typeof(uint))
        {
            uint s;
            if (uint.TryParse(input, out s))
                return s;
        }

        if (underlyingType == typeof(ulong))
        {
            ulong s;
            if (ulong.TryParse(input, out s))
                return s;
        }

        if (underlyingType == typeof(long))
        {
            long s;
            if (long.TryParse(input, out s))
                return s;
        }

        if (underlyingType == typeof(short))
        {
            short s;
            if (short.TryParse(input, out s))
                return s;
        }

        if (underlyingType == typeof(ushort))
        {
            ushort s;
            if (ushort.TryParse(input, out s))
                return s;
        }

        if (underlyingType == typeof(byte))
        {
            byte s;
            if (byte.TryParse(input, out s))
                return s;
        }

        if (underlyingType == typeof(sbyte))
        {
            sbyte s;
            if (sbyte.TryParse(input, out s))
                return s;
        }

        return null;
    }

    private static bool EnumToObject(Type type, Type underlyingType, string[] names, Array values, string input, out object value)
    {
        for (int i = 0; i < names.Length; i++)
        {
            if (string.Compare(names[i], input, StringComparison.OrdinalIgnoreCase) == 0)
            {
                value = values.GetValue(i);
                return true;
            }
        }

        if ((char.IsDigit(input[0]) || (input[0] == '-')) || (input[0] == '+'))
        {
            object obj = EnumToObject(underlyingType, input);
            if (obj == null)
            {
                value = Activator.CreateInstance(type);
                return false;
            }
            value = obj;
            return true;
        }

        value = Activator.CreateInstance(type);
        return false;
    }
3
  • 1
    you provided the best implementation and I have used it for my own purposes; however, I am wondering why you use Activator.CreateInstance(type) to create the default enum value and not Enum.ToObject(type, 0). Just a matter of taste? Sep 13, 2011 at 13:31
  • 1
    @Pierre - Hmmm... no, it just seemed more natural at that time :-) Maybe Enum.ToObject is faster since it's internally using an an internal call InternalBoxEnum? I never checked that... Sep 13, 2011 at 13:46
  • 2
    As mentioned below, but not really visible: As of .Net 4 Enum.TryParse is available and works without extra coding. More information is available from MSDN: msdn.microsoft.com/library/vstudio/dd991317%28v=vs.100%29.aspx
    – Christian
    Sep 19, 2013 at 9:34
17

In the end you have to implement this around Enum.GetNames:

public bool TryParseEnum<T>(string str, bool caseSensitive, out T value) where T : struct {
    // Can't make this a type constraint...
    if (!typeof(T).IsEnum) {
        throw new ArgumentException("Type parameter must be an enum");
    }
    var names = Enum.GetNames(typeof(T));
    value = (Enum.GetValues(typeof(T)) as T[])[0];  // For want of a better default
    foreach (var name in names) {
        if (String.Equals(name, str, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)) {
            value = (T)Enum.Parse(typeof(T), name);
            return true;
        }
    }
    return false;
}

Additional notes:

  • Enum.TryParse is included in .NET 4. See here http://msdn.microsoft.com/library/dd991876(VS.100).aspx
  • Another approach would be to directly wrap Enum.Parse catching the exception thrown when it fails. This could be faster when a match is found, but will likely to slower if not. Depending on the data you are processing this may or may not be a net improvement.

EDIT: Just seen a better implementation on this, which caches the necessary information: http://damieng.com/blog/2010/10/17/enums-better-syntax-improved-performance-and-tryparse-in-net-3-5

2
  • I was going to suggest using default(T) to set the default value. Turns out this wouldn't work for all enums. E.g. If the underlying type for the enum was int default(T) will always return 0, which may or may not be valid for the enum. Nov 24, 2009 at 21:51
  • The implementation at Damieng's blog does not support enums with the Flags attribute.
    – Uwe Keim
    Jul 2, 2013 at 9:16
11

Based on .NET 4.5

Sample code below

using System;

enum Importance
{
    None,
    Low,
    Medium,
    Critical
}

class Program
{
    static void Main()
    {
    // The input value.
    string value = "Medium";

    // An unitialized variable.
    Importance importance;

    // Call Enum.TryParse method.
    if (Enum.TryParse(value, out importance))
    {
        // We now have an enum type.
        Console.WriteLine(importance == Importance.Medium);
    }
    }
}

Reference : http://www.dotnetperls.com/enum-parse

6
enum EnumStatus
{
    NAO_INFORMADO = 0,
    ENCONTRADO = 1,
    BLOQUEADA_PELO_ENTREGADOR = 2,
    DISPOSITIVO_DESABILITADO = 3,
    ERRO_INTERNO = 4,
    AGARDANDO = 5
}

...

if (Enum.TryParse<EnumStatus>(item.status, out status)) {

}
2
  • I am getting, status does not exists in the current context
    – Muflix
    May 25, 2021 at 18:06
  • In my case this works instead Enum.TryParse<EnumStatus>(someStatusAsInt.ToString(), out EnumStatus status)
    – Muflix
    May 25, 2021 at 18:08
4

I have an optimised implementation you could use in UnconstrainedMelody. Effectively it's just caching the list of names, but it's doing so in a nice, strongly typed, generically constrained way :)

2

There's currently no out of the box Enum.TryParse. This has been requested on Connect (Still no Enum.TryParse) and got a response indicating possible inclusion in the next framework after .NET 3.5. You'll have to implement the suggested workarounds for now.

1

The only way to avoid exception handling is to use the GetNames() method, and we all know that exceptions shouldn't be abused for common application logic :)

1
  • 1
    It's not the only way. Enum.IsDefined(..) will prevent exceptions being thrown in user code.
    – Thorarin
    Jul 4, 2009 at 17:21
1

Is caching a dynamically generated function/dictionary permissable?

Because you don't (appear to) know the type of the enum ahead of time, the first execution could generate something subsequent executions could take advantage of.

You could even cache the result of Enum.GetNames()

Are you trying to optimize for CPU or Memory? Do you really need to?

1
  • Idea is to optimize CPU. Agree that i can do it at the cost memory. But its not the solution i am looking for. Thanks. Jul 4, 2009 at 17:31
0

Have a look at the Enum class (struct ? ) itself. There is a Parse method on that but I'm not sure about a tryparse.

1
  • I know about Enum.Parse(typeof(TEnum), strEnumValue) method. It throws ArgumentException if strEnumValue is not valid. Looking for TryParse........ Jul 4, 2009 at 16:38
0

As others already said, if you don't use Try&Catch, you need to use IsDefined or GetNames... Here are some samples...they basically are all the same, the first one handling nullable enums. I prefer the 2nd one as it's an extension on strings, not enums...but you can mix them as you want!

  • www.objectreference.net/post/Enum-TryParse-Extension-Method.aspx
  • flatlinerdoa.spaces.live.com/blog/cns!17124D03A9A052B0!605.entry
  • mironabramson.com/blog/post/2008/03/Another-version-for-the-missing-method-EnumTryParse.aspx
  • lazyloading.blogspot.com/2008/04/enumtryparse-with-net-35-extension.html
0

There is not a TryParse because the Enum's type is not known until runtime. A TryParse that follows the same methodology as say the Date.TryParse method would throw an implicit conversion error on the ByRef parameter.

I suggest doing something like this:

//1 line call to get value
MyEnums enumValue = (Sections)EnumValue(typeof(Sections), myEnumTextValue, MyEnums.SomeEnumDefault);

//Put this somewhere where you can reuse
public static object EnumValue(System.Type enumType, string value, object NotDefinedReplacement)
{
    if (Enum.IsDefined(enumType, value)) {
        return Enum.Parse(enumType, value);
    } else {
        return Enum.Parse(enumType, NotDefinedReplacement);
    }
}
1
  • For Try methods whose results may be value types, or where null may be legitimate result (e.g. Dictionary.TryGetValue, which has both such traits), the normal pattern is for a Try` method to return bool, and pass the result as an out parameter. For those which return class types where null is not a valid result, there's no difficulty using a null return to indicate failure.
    – supercat
    Dec 18, 2012 at 18:48
-2

This method will convert a type of enum:

  public static TEnum ToEnum<TEnum>(object EnumValue, TEnum defaultValue)
    {
        if (!Enum.IsDefined(typeof(TEnum), EnumValue))
        {
            Type enumType = Enum.GetUnderlyingType(typeof(TEnum));
            if ( EnumValue.GetType() == enumType )
            {
                string name = Enum.GetName(typeof(HLink.ViewModels.ClaimHeaderViewModel.ClaimStatus), EnumValue);
                if( name != null)
                    return (TEnum)Enum.Parse(typeof(TEnum), name);
                return defaultValue;
            }
        }
        return (TEnum)Enum.Parse(typeof(TEnum), EnumValue.ToString());
    } 

It checks the underlying type and get the name against it to parse. If everything fails it will return default value.

1
  • 4
    what is this doing "Enum.GetName(typeof(HLink.ViewModels.ClaimHeaderViewModel.ClaimStatus), EnumValue)" Probably some dependency on your local code. Jun 9, 2010 at 16:28

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.