Although yourEdit
The question about constraining T to an Enum has now superbly been answered by VivekJulien Lebosquain. I would also like to extend his answer with ignoreCase, defaultValue and the additional commentsoptional arguments, I think your resulting functionwhile adding ParseEnumTryParse can be improvedand ParseOrDefault.
public abstract class ConstrainedEnumParser<TClass> where TClass : class // value type constraint S ("TEnum") depends on reference type T ("TClass") [and on struct] { // internal constructor, to prevent this class from being inherited outside this code internal ConstrainedEnumParser() {} // Parse using pragmatic/adhoc hard cast: // - struct + class = enum // - 'guaranteed' call from derived <System.Enum>-constrained type EnumUtils public static TEnum Parse<TEnum>(string value, bool ignoreCase = false) where TEnum : struct, TClass { return (TEnum)Enum.Parse(typeof(TEnum), value, ignoreCase); } public static bool TryParse<TEnum>(string value, out TEnum result, bool ignoreCase = false, TEnum defaultValue = default(TEnum)) where TEnum : struct, TClass // value type constraint S depending on T { var didParse = Enum.TryParse(value, ignoreCase, out result); if (didParse == false) { result = defaultValue; } return didParse; } public static TEnum ParseOrDefault<TEnum>(string value, bool ignoreCase = false, TEnum defaultValue = default(TEnum)) where TEnum : struct, TClass // value type constraint S depending on T { if (string.IsNullOrEmpty(value)) { return defaultValue; } TEnum result; if (Enum.TryParse(value, ignoreCase, out result)) { return result; } return defaultValue; } } public class EnumUtils: ConstrainedEnumParser<System.Enum> // reference type constraint to any <System.Enum> { // call to parse will then contain constraint to specific <System.Enum>-class }
Examples of usage:
WeekDay parsedDayOrArgumentException = EnumUtils.Parse<WeekDay>("monday", ignoreCase:true); WeekDay parsedDayOrDefault; bool didParse = EnumUtils.TryParse<WeekDay>("clubs", out parsedDayOrDefault, ignoreCase:true); parsedDayOrDefault = EnumUtils.ParseOrDefault<WeekDay>("friday", ignoreCase:true, defaultValue:WeekDay.Sunday);
Old
My old improvements on Vivek's answer by thoseusing the comments and 'new' developments: