Jatin kacha's Blog

How to convert value to Enum

Posted on: October 2, 2010

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…

Advertisements

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: