web 2.0

Enum String Values Revised

Hi,

In this article I’ll provide an improvement about my previous post talking about String Values from Enumerations.

Previously we was only able to handle String Values for Enums but with the following we are now able to handle any type of values like DateTime, String, Decimal, etc..

Here is a Sample of Custom Enum :

public enum MyStringEnum
{
    [EnumValue("Hello")]
    Foo,
    [EnumValue("Merry Christmas")]
    Something
}

public enum MyDateTimeEnum
{
    [EnumValue("12/30/2008")]
    Foo,
    [EnumValue("12/01/2008")]
    Something
}

Note : We must still using String Values in EnumValue Constructor since Attribute cannot be Generic and Constructor Parameter must be a constant expression, typeof expression or array creation expression.

 

The EnumValueAttribute is the same as described in my previous post.

public class EnumValueAttribute : Attribute
{
    #region Public Properties

    public String Value { get; private set; }

    #endregion

    public EnumValueAttribute(String val)
    {
        Value = val;
    }
}

The Trick resides in the GetValue Extension Method which is now Generic and use TypeConverter

public static T GetValue<T>(this Enum o)
{
    Type type = o.GetType();
    FieldInfo fieldInfo = type.GetField(o.ToString());
    EnumValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
        typeof(EnumValueAttribute), false) as EnumValueAttribute[];

    if (attribs.Length > 0)
    {
        return (T)Convert.ChangeType(attribs[0].Value, typeof(T));
    }
    else
    {
        return default(T);
    }
}

Now we can use it simply like that :

MyStringEnum StringEnum = MyStringEnum.Foo;
String s = StringEnum.GetValue<String>();
Console.WriteLine(s);

MyDateTimeEnum DateEnum = MyDateTimeEnum.Something;
DateTime date = DateEnum.GetValue<DateTime>();
Console.WriteLine(date);

 

Hope this help’s!.



Views(1447)

kick it on DotNetKicks.com

Share/Save/Bookmark Subscribe

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C#

Comments

Add comment


 

biuquote
Loading



Technorati Profile