Sunday, November 14, 2010

How to convert value to Enum

How to convert a value into Enum?

In project, we sometime come across a kind of situation where we need to convert some value to Enum and an Enum object into certain value.

One solution to this is we can write chunk of switch-case statement and return the desired result.

But is there any rationalize method to achieve this? Yes here is the piece of code that you may find it useful. I have implemented it in many of my project and it really helps me reduce some overloaded work for me.

So here is that code for you in which I demonstrate how you can convert a value into Enum object.

using System;

using System.Collections.Generic;

using System.Linq;

public
static
class
EnumsConverter

{


public
static T ConvertValueToEnum<T>(object value, T defaultValue)

{


Type enumType = Reflection.ExtractEnumType(typeof(T));


if (enumType == null)

{


throw
new
ArgumentException("Type T is not an enumeration", "T");

}


try

{


return (T)Enum.Parse(enumType, value.ToString());

}


catch (ArgumentException)

{


return defaultValue;

}

}


public
static T ConvertValueToEnum<T>(object value)

{


Type enumType = Reflection.ExtractEnumType(typeof(T));


if (enumType == null)

{


throw
new
ArgumentException("Type T is not an enumeration", "T");

}


return (T)Enum.Parse(enumType, value.ToString());

}

}

Here there are two overloaded methods. All you have to do is pass your desired enumeration object. The method itself will identify and return attached valued to that particular Enum object.

Happy programming…

 

No comments: