Object Reference .NET

ref this.Object

enum to friendly string extension method

clock June 3, 2008 12:05 by author 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)
    ArchiveRecord();


is a lot more clearer and meaningful making it easier to maintain than

if (Status == 3)
    ArchiveRecord()


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
{
    None,
    ManAndVan,
    FullRemoval,
    FullRemovalsAndPacking
}
 
public static class RemovalTypeEnum
{
    /// <summary>
    /// Returns a friendly enum name
    /// </summary>
    public static string ToFriendlyString(this RemovalType removalType)
    {
        switch (removalType)
        {
            case RemovalType.ManAndVan:
                return "Man & Van Service";
            case RemovalType.FullRemoval:
                return "Standerd removals service";
            case RemovalType.FullRemovalsAndPacking:
                return "Full removals and packing service";
            default:
                return removalType.ToString();
        }
    }
}

 

RemovalType removalType = RemovalType.ManAndVan;
removalType.ToFriendlyString()


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() %>



kick it on DotNetKicks.com



Enum TryParse Extension Method

clock April 21, 2008 14:43 by author 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);
    int intEnumValue;
    if (Int32.TryParse(valueToParse, out intEnumValue))
    {
        if (Enum.IsDefined(typeof(T), intEnumValue))
        {
            returnValue = (T)(object)intEnumValue;
            return true;
        }
    }
    return false;
}


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).

kick it on DotNetKicks.com

 


Advertisment


RecentComments

Comment RSS

Sign in