From this answer:
https://stackoverflow.com/a/15738041/1250301
To this question:
How to get name of property which our attribute is set?
You can use CallerMemberName
to figure out which property an attribute is attached too. Which is pretty cool. Unfortunately, it doesn't seem to work with enums. For example:
https://dotnetfiddle.net/B69FCx
public static void Main()
{
var mi = typeof(MyEnum).GetMember("Value1");
var attr = mi[0].GetCustomAttribute<FooAttribute>();
mi = typeof(Bar).GetMember("SomeProp");
attr = mi[0].GetCustomAttribute<FooAttribute>();
}
public class Bar
{
[Foo]
public string SomeProp { get; set; }
}
public class FooAttribute : Attribute
{
public FooAttribute([CallerMemberName]string propName = null)
{
Console.WriteLine("Propname = " + propName);
}
}
enum MyEnum
{
[Foo]
Value1,
[Foo]
Value2
};
propName
when you access it for a MyEnum
is null, but for the class Bar
it works as expected (i.e. it's SomeProp
). Is there a way to make this or something similar work for an enum? Or am I stuck with adding a property to FooAttribute
and setting it when I add the property to the enum:
public class FooAttribute : Attribute
{
public MyEnum AttachedTo { get; set; }
}
enum MyEnum
{
[Foo(AttachedTo = MyEnum.Value1)]
Value1,
[Foo(AttachedTo = MyEnum.Value2)]
Value2
};
Which is tedious and has potential to be error prone.