Friday, July 24, 2015

Setting a Default Value for Enums in C#

Enums can be very useful in cases like where you want to maintain a set of named constants. Imagine you have following values, “Daily, Weekly, SemiMonthly etc” and you want to display these inside a drop down list. And for the dropdown you need to set up a default value. You can easily use enum for this. Of course I am sure all of you must be aware of how to use enums and from this post let’s see how we can set up a default value for an enum and how to get that default value.

So I have the following enum and please note the DefaultValueAttribute which I used to decorate my enum "Period" with.
public enum Period
So only by decorating the enum with DefaultValueAttribute and setting the default value, now my enum "Period" has a default value which is “Monthly”. Now let’s see how I can retrieve it.
public static T GetEnumDefaultValue<T>() where T : struct
    DefaultValueAttribute[] attributes = typeof(T).GetCustomAttributes(typeof(DefaultValueAttribute), false) as DefaultValueAttribute[];

    if (attributes != null && attributes.Length > 0)
        return (T)attributes[0].Value;
    return default(T);
Here I have a generic method, I have applied a constraint on the type argument where T : struct and that’s because enums are of value types. Then after getting the type of type argument, I am getting the list of attributes applied to it. Since the only attribute applied is a DefaultValueAttribute, I can cast the result set into an array of DefaultValueAttribute. Then if the result is not null and if it is elements, I am getting the value of first element. Else I am returning the enum which has the value 0 which is the default by nature of course.

Now let’s see how we can call this method. It's pretty simple.
static void Main(string[] args)
   Period period = GetEnumDefaultValue<Period>();
And the output is as expected.
Happy Coding.