Fast Enum.TryParse implementation

I recently saw a post asking why there wasn’t an Enum.TryParse in .NET. I’ve forgotten where the post was, but I found myself needing this so I implemented it myself. It notably doesn’t use a try { } catch { } block so performance should be pretty good.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public static class EnumExtensions
    public static bool EnumTryParse<T>(this string enumText, out T enumValue) 
        where T : struct
        enumValue = default(T);
        if (Enum.IsDefined(typeof(T), enumText))
            enumValue = (T)Enum.Parse(typeof(T), enumText);
            return true;
        return false;


string unparsedEnumText = "SomeText";
MyCoolEnum parsedEnum;
if (unparsedEnumText.EnumTryParse(out parsedEnum))
    Console.WriteLine("Parsed OK as " + parsedEnum.ToString());

Note: .NET doesn’t allow for System.Enum to be defined as a type constraint so be careful!


Update: Changed to use Enum.IsDefined instead of Enum.GetNames

  1. #1 by Daniel on November 25, 2009 - 9:38 am

    Try adding something like the following to check the type at runtime. It isn\’t as good as a type constraint, but reduces the risk a bit.if (!typeof(T).IsEnum) { throw new ArgumentException("Type parameter must be an enum"); }

  2. #2 by Andrew on December 14, 2009 - 9:28 am

    Good point, that might make the exception perhaps a bit more predictable (I believe it would currently throw an InvalidCastException).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: