Skip to main content

Enum With String Values In C#




In this post i will show how to assign string value to enum(In C# you cannot have an enum that has string values)
Step1
First I created the new custom attribute class, the source is below:
Step2
Then I created a new which I will use to get the string value for an enums value:



using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Reflection;
public class StringValueAttribute : Attribute
{
public string StringValue;

public StringValueAttribute(string value)
{
this.StringValue = value;
}
}
public static class Util
{
public static string GetStringValue(Enum value)
{
// Get the type
Type type = value.GetType();

// Get fieldinfo for this type
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;
}

}


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EnumToString.aspx.cs" Inherits="EnumToString" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
</form>
</body>
</html>





using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class EnumToString : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
string val = Util.GetStringValue(Test.Something);
Response.Write(val);
}

}

public enum Test : int
{
[StringValue("Value1")]
Foo = 1,
[StringValue("Value2")]
Something = 2
}

Comments

Popular posts from this blog