Reputation: 2720
I have created an Enum and want to read the text value from it. The Enum is as below:
public enum MethodID
{
/// <summary>
/// The type of request being done. Inquiry.
/// </summary>
[EnumTextValue("01")]
Inquiry,
/// <summary>
/// The type of request being done. Update
/// </summary>
[EnumTextValue("02")]
Update,
}
Now I want to assign the value of enum to a request object methodID. I tried the following code, but it didnt worked:
request.ID = Enum.GetName(typeof(MethodID), MethodID.Inquiry);
What I want is to assign the value "01" to the data member of request data contract (request.ID) that I will fetch from the Enum MethodID. How will I get this? Please help
Upvotes: 2
Views: 3548
Reputation: 1553
If you want just to get int value then you can declare enum as
public enum MethodID
{
[EnumTextValue("01")]
Inquiry = 1,
[EnumTextValue("02")]
Update = 2,
}
And then use casting to int:
ind id = (int)MethodID.Inquiry;
If you want to get string value from attribute then this is the static helper method
///<summary>
/// Allows the discovery of an enumeration text value based on the <c>EnumTextValueAttribute</c>
///</summary>
/// <param name="e">The enum to get the reader friendly text value for.</param>
/// <returns><see cref="System.String"/> </returns>
public static string GetEnumTextValue(Enum e)
{
string ret = "";
Type t = e.GetType();
MemberInfo[] members = t.GetMember(e.ToString());
if (members.Length == 1)
{
object[] attrs = members[0].GetCustomAttributes(typeof (EnumTextValueAttribute), false);
if (attrs.Length == 1)
{
ret = ((EnumTextValueAttribute)attrs[0]).Text;
}
}
return ret;
}
Upvotes: 6
Reputation: 4327
Try this
string myEnum = MethodID.Inquiry.ToString();
int value = (int)MethodID.Inquiry;
Some more info on how to add custom atributes and using them in code http://blogs.msdn.com/b/abhinaba/archive/2005/10/20/c-enum-and-overriding-tostring-on-it.aspx
Upvotes: 1