April 21, 2008 14:43 by Magz
TryParse method is very helpful if you need to convert string representation of a value to a value itself. TryParse is better than Parse method because it doesn’t throw any exceptions and just returns a Boolean value to indicate weather the parsing was successful. Surprisingly there is no TryParse method available to use for Enum and this is where extension method can be extremely useful.
public static bool TryParse<T>(this Enum theEnum, string valueToParse, out T returnValue)
returnValue = default(T);
if (Int32.TryParse(valueToParse, out intEnumValue))
if (Enum.IsDefined(typeof(T), intEnumValue))
returnValue = (T)(object)intEnumValue;
Now it’s time to test our extension method! Here I have a simple UserType Enumeration
public enum UserType
None = 0,
Administrator = 1,
Manager = 2,
Consultant = 3
I want to parse QueryString parameter usertype and store the result in currentUserType variable.
currentUserType.TryParse(Request.QueryString["usertype"], out currentUserType);
if Request.QueryString["usertype"] is invalid UserType then currentUserType variable will be set to None (0).