Hi,
I need to write an enumeration collection that is capable of enumerating over a set of string values and returning the property name and value. Can anyone provide me an example of how to write this?
PenskyFile
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VikramPosted Jun 17, 2010, 1:47 AM
Hi,
I did similar to what is you are expecting.
First write one Class which is derived from Attribute.
public class StringValueAttribute : Attribute
{
#region
Propertiespublic string StringValue { get; protected set; }
#endregion
#region
Constructorpublic StringValueAttribute(string value)
{
this.StringValue = value;
}
#endregion
}
public
static class Extension{
public static string GetStringValue(this 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;
}
}
Now Define Any Enum as following:
public enum Industry
{
[StringValue("Finance")]
fin,
[StringValue("IT")]
it,
[StringValue("Telecom")]
tel
}
And Now you will access property names and values as follows,
string val = Industry.fin.GetStringValue();
The val contains string as "Finance"
I hope this is what your requirement.
Regards,
VIkram