June 3, 2008 12:05 by Naz
We use enums quite extensively in our application as they are great for representing integral values in a strongly typed way using symbolic names eg.
if (Status == UserStatus.NotLoggedInAYear)
is a lot more clearer and meaningful making it easier to maintain than
if (Status == 3)
The enum names are not very friendly to the user and I recently read a some good articles creating user friendly strings for enum values and Enum description values which tried to solve this problem.
I think i've found a better solution to this problem using extension methods.
public enum RemovalType
public static class RemovalTypeEnum
/// Returns a friendly enum name
public static string ToFriendlyString(this RemovalType removalType)
return "Man & Van Service";
return "Standerd removals service";
return "Full removals and packing service";
RemovalType removalType = RemovalType.ManAndVan;
This implementation creates an extension method on the actual enum "RemovalType" which then allows you to call a ToFriendlyString() on the instance of all enums of that type I think this a more fluid implementation and also means better performance compared to the other implementations as it doesn't need to use reflection.
You will notive i've decided to leave the default return value to call ToString() on the enum value which means you only need to implement the values that need to be made friendlier.
You can also call it easily inside databinded controls in the aspx page.
<%# ((RemovalType)Eval("ServiceType")).ToFriendlyString() %>
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).