Once you have added a string attribute extension to enum, you may find it useful to add multiple attributes on a given enumerated item. To accomplish that all you need are some minor adjustments to the core process, which is described in part I of this blog sequel. We’ll discuss those adjustments with examples here. For example, if you wanted to add the hex values to our previously used enum, as shown below:
public enum SampleColor
{
[StringValue("Hex", "#FF0000")]
[StringValue("R")]
Red = 1,
[StringValue("G")]
[StringValue("Hex", "#008000")]
Green = 2,
[StringValue("B")]
[StringValue("Hex", "#0000FF")]
Blue = 3,
MultiColor = 4
}
You need to modify the custom attribute subclass in a couple of ways. First, add an AttributeUsage attribute to allow duplicate attributes to the same field. Then add a constructor to accept a key/value pair and finally, provide an accessor to get the key. These changes are incorporated into the original StringValueAttribute class and sampled below:
[AttributeUsage(AttributeTargets.Field , AllowMultiple = true)]
public class StringValueAttribute : Attribute
{
private readonly string _key;
private readonly string _value;public string Key
{
get { return _key; }
}
public string Value
{
get { return _value; }
}public StringValueAttribute(string pValue)
{
this._value = pValue;
}
public StringValueAttribute(string pKey, string pValue)
: this(pValue)
{
this._key = pKey;
}
}
Now, you can add another extension method to enum to extract the value, given a key, as illustrated in the sample below:
public static object GetStringAttributeValue(this Enum enumValue, string key)
{
if (key == null)
return "Unavailable";Type enumType = enumValue.GetType();
FieldInfo fieldInfo = enumType.GetField(Enum.GetName(enumType, enumValue), BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public | BindingFlags.NonPublic);
object[] customAttributes = fieldInfo.GetCustomAttributes(false);
for (int i = 0; i < customAttributes.Length; i++)
{
StringValueAttribute attribute = customAttributes[i] as StringValueAttribute;
if (attribute.Key == key)
return attribute.Value;
}
return "Unavailable";
}
That’s it and you are done. You can now use the new extension as simply as:
SampleColor.Green.GetStringAttributeValue("Hex")