Read Time1 Minute, 32 Second

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…


NOTE : Also visit www.dhanashree.com


If you are in need of any
Web Development feel free to Inquire us . Dhanashree Inc. Expertise in Asp.net Development, Php Development,
Website designing
, Open Source customisation. Dhanashree Inc can be our offshore development company /
outsourcing web development company, hire dedicated web programmers.


Above information is for knowledge sharing if you have problem / issue / suggestion please intimate us with details for proper and prompt action.

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Close