Enum.Parse
When you parse an enum in .NET, if you pass in a value which isn’t in the enum, you’ll still get an enum value out again.
This piece of code will write out ‘3’.
enum Example { Value0 = 0, Value1 = 1 } public static void RunSnippet() { Console.WriteLine( Enum.Parse(typeof(Example), "3") ); } However, there is another method 'IsDefined' which will tell you if the value held by the enum is a valid value. So this method will parse your enum, and will return the default if the value isn't valid: private static T ParseEnum(string value) { T t = (T)Enum.Parse(typeof(T), value); if (Enum.IsDefined(typeof(T), t)) { return t; } return default(T); }
Reply
You must be logged in to post a comment.