Hi,

recently I was doing some code about enum parsing, I think  an operation everyone’s involved in one time. After some Googlin’ I found some well or not well done examples. Doing a generic parse method is too simple as you can see on Windows.NET Blog post but you don’t have no type check code or constraints, or something about a default check value, so I done my implementation, which assumes that the target enum type has some well defined constraints like: inheriting from the struct base type,  having an Undefined or a None element.. if not the first enum member is assumed as the default one. Here is my little code

/// <summary> /// Translates from a string name enum member /// to the given gene ric enumeration Type /// </summary> /// <param name="name">the name string to translate</param> /// <returns></returns> private T TranslateFrom<T>(string name) where T : struct { const string DEFAULT = "Undefined"; const string NONE = "None"; Type enumType = typeof(T); T result; if (Enum.IsDefined(enumType, command)) { result = (T)Enum.Parse(enumType, command, true); } else { string defaultName = null; if (Enum.IsDefined(enumType, DEFAULT)) defaultName = DEFAULT; else if (Enum.IsDefined(enumType, NONE)) defaultName = NONE; if (!string.IsNullOrEmpty(defaultName)) { result = (T)Enum.Parse(enumType, command, true); } else { string[] values = Enum.GetNames(enumType); result = (T)Enum.Parse(enumType, values[0], true); } } return result; }

This is just a little helper method I wish to share, enjoy!

Ciao

Tags:

Advertisements