Thursday, July 16, 2009

Return String value from enum instead of int value

Hello Frnds,
In my recent project,there is a requirement to get enum string value instead of int. As u all know that enum which will return integer value.
Finally I got the solution. Here I place the code of that customize enum. I hopes it will help you.

Class Name: Enums.cs
public enum HotelActivity : int
{
[StringValue("family friendly")]
Family_Friendly=1
,[StringValue("adults only")]
Adults_Only=2
}

Class Name: StringValueAttribute.cs
public class StringValueAttribute : Attribute
{

public string StringValue { get; protected set; }

public StringValueAttribute(string value)
{
this.StringValue = value;
}
}


Class Name: Extensions.cs
public static class Extensions
{
public static string GetStringValue(this Enum value)
{
// Get the type
Type type = value.GetType();

// Get fieldinfo for this type
System.Reflection.FieldInfo fieldInfo = type.GetField(value.ToString());

// Get the stringvalue attributes
StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(StringValueAttribute), false) as StringValueAttribute[];

// Return the first if there was a match.
return attribs.Length > 0 ? attribs[0].StringValue : null;
}
}

default.aspx.cs
public partial class default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Framework.Enums.HotelActivity.Family_Friendly.GetStringValue());
}
}

Try to implement this code and enjoy :)

Regards,
Kinjal Shah

No comments: