In many of the projects, there is a requirement to get the string values from the enum definition.
One attribute that can be used off-the-shelf is [Flags] attribute. But this attribute gives only the string representation of the enum variable, which means you cannot have spaces or long strings.
So to overcome this, one can write a handy enum extension for this.
Consider the following enum,
internal enum XlColumnHeaders
{
[StringValue("Section")]
xlSection = 1,
[StringValue("Question Text")]
xlQuestionText = 2,
[StringValue("Free Text")]
xlFreeText = 3,
[StringValue("Yes No")]
xlYesNo = 4,
}
Now whenever I wish to get a string representation of xlSection, I should get "Section". Similarly, for xlQuestionText I should get "Question Text" [Note: the space between the 2 words].
To achieve the above result, Create a static class with a public static method as follows.
static class StringEnum
{
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;
}
}
Usage:
XlColumnHeaders temp = new XlColumnHeaders();
temp = XlColumnHeaders.xlQuestionText;
temp.GetStringValue(); // this would return "Question Text"
Hope this post is helpful.
No comments:
Post a Comment