CJ

The circle of life – ** .Net – Training – MOSS **

  • Past Post

  • Vistor Locations

Enum value with spaces c#

Posted by Clayton James on September 8, 2010

Have you ever wanted to display a friendly Enum name that included spaces.

C# doesn’t allow spaces in Enum’s, just like variables. However, thanks to c# extension methods we can create a new method that returns the Description Attribute.

Apply descriptions which may be different to the enum value. Notice the space.
public enum WorkType

{
[Description(“Service Delivery”)]
ServiceDelivery,
Project,
Unavailable
}

Create the extension method
//used to get the description from enum fields
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value); if (name != null)
{
FieldInfo field = type.GetField(name);
if (field != null)
{
DescriptionAttribute attr =
Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
}

Use it in your code
string serivceDelivery = WorkType.ServiceDelivery.GetDescription();

Advertisements

One Response to “Enum value with spaces c#”

  1. Trang said

    We have decided to open our POWERFUL and PRIVATE web traffic system to the public for a limited time! You can sign up for our UP SCALE network with a free trial as we get started with the public’s orders. Imagine how your bank account will look when your website gets the traffic it deserves. Visit us today: http://voxseo.com/traffic/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: