attributes on enum members?

  • Thread starter Thread starter Simon Dahlbacka
  • Start date Start date
S

Simon Dahlbacka

Hi,

I have an occasion where it would be useful to add attributes to
individual enum members, and I can do that very well enough, the
problem is: how do I access them "after the fact"?

the obvious

Thing foo = Thing.Bar;
object[] attrs = foo.GetType().GetCustomAttributes(false);

does not work for obvious reasons..

Do I have to rethink my approach to the problem (i.e. skip the use of
attributes on enum members), or is there a way to make it work?
 
IIRC, they manifest as static fields obtainable via reflection:

enum TestEnum { A, B, C }
static void Main()
{
FieldInfo fi = typeof(TestEnum).GetField("A");
}

From here, the FieldInfo has an Attributes property

Marc
 
FieldInfo fi = typeof(TestEnum).GetField("A");

thank you!

that was the pointer I needed to get it working.. (I still needed
fi.GetCustomAttributes(...) though)

/Simon
 
Oops; yep GetCustomAttributes is the way... I was thinking of
PropertyDescriptor where "Attributes" is the set of custom attributes; for
the reflection {blah}Info classes you are entirely correct. I guess I've
been messing with the component-model too much lately ;-p

Oh well, I got the static fields bit right!

Marc
 
Simon,
I have an occasion where it would be useful to add attributes to
individual enum members,

Could you post an example of an enum that has attributes added please?
It sounds like something that might be quite useful, but I've not come
across it before.

Cheers,

Richard
 
example with attributes; note that they won't be used by the component
model, so you would need to explicitely make use of the attributes
yourself...

[AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field)]
public class EnumDisplayNameAttribute : DisplayNameAttribute {
public EnumDisplayNameAttribute(string displayName) : base(displayName)
{ }
}
enum TestEnum
{
[EnumDisplayName("Test A")]
TestA,
[EnumDisplayName("Test B")]
TestB,
[EnumDisplayName("Test C")]
TestC
}
class Test
{
static void Main()
{
foreach(FieldInfo fi in typeof(TestEnum).GetFields()) {
string displayName = fi.Name;
foreach (EnumDisplayNameAttribute attrib in
fi.GetCustomAttributes(typeof(EnumDisplayNameAttribute), true))
{
displayName = attrib.DisplayName;
break;
}
Debug.WriteLine(fi.Name + "\t" + displayName);
}
}
}
 
Back
Top