About the author

Miron Abramson
Software Engineer,
CTO at PixeliT
and .NET addicted for long time.
Open source projects:
MbCompression - Compression library

Recent comments



The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2018

Creative Commons License

Blog Flux Directory
Technology Blogs - Blog Top Sites

Another version for the missing method: Enum.TryParse (in C#)

The 'TryParse' methods for all types are very useful and I'm using them all the time. It's very surprising that Microsoft didn't include in the Framework a method that can be very useful: Enum.TryParse. A lot of coders find themself writing from time to time  'parsing' methods for their enums. Something like that:

public enum ImageType

public static ImageType ParseImagetype(string typeName)
    typeName = typeName.ToLower();
    switch (typeName)
        case "Gif":
            return ImageType.Gif;
        case "png":
            return ImageType.Png;
        case "jpg":
            return ImageType.Jpg;

 Thats work fine, but you need to write such 'parsing' method for each enum you have.  The Enum class have it's own 'parsing' method (that luckly have 'IgnoreCase' flag), but not a TryParse method. The commonly fix around is to put the Enum.Parse method inside Try & Catch, what is, of cource, give bad performance in case of failure. The Enum class have also a method 'IsDefined' that return an indication if a value is exists in the enum. unfortunately, this method doesn't have an  'IgnoreCase' flag.

So, trying to put all this 'knowledge' together, I wrote my own generic version for 'Enum.TryParse' method that is also ignore case and not using try & catch:

public static bool EnumTryParse<T>(string strType,out T result)
    string strTypeFixed = strType.Replace(' ', '_');
    if (Enum.IsDefined(typeof(T), strTypeFixed))
        result = (T)Enum.Parse(typeof(T), strTypeFixed, true);
        return true;
        foreach (string value in Enum.GetNames(typeof(T)))
            if (value.Equals(strTypeFixed, StringComparison.OrdinalIgnoreCase))
                result = (T)Enum.Parse(typeof(T), value);
                return true;
        result = default(T);
        return false;

The line 'string strTypeFixed = strType.Replace(' ', '_');' is because I was getting the data from third party WebService that send the enum strings with spaces, what is not allowed in enum, so my enums had '_' instead of  spaces.

To parse a ImageType (from the example above) just use it like this:

ImageType type;
if (Utils.EnumTryParse<ImageType>(typeName, out type))
    return type;
return ImageType.Jpg;

Currently rated 4.8 by 4 people

  • Currently 4.75/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: C#
Posted by Miron on Saturday, March 08, 2008 8:54 AM
Permalink | Comments (14) | Post RSSRSS comment feed