How do I get the member to which my custom attribute was applied?
Posted
by Sarah Vessels
on Stack Overflow
See other posts from Stack Overflow
or by Sarah Vessels
Published on 2010-01-30T18:34:53Z
Indexed on
2010/03/30
14:33 UTC
Read the original article
Hit count: 504
I'm creating a custom attribute in C# and I want to do different things based on whether the attribute is applied to a method versus a property. At first I was going to do new StackTrace().GetFrame(1).GetMethod()
in my custom attribute constructor to see what method called the attribute constructor, but now I'm unsure what that will give me. What if the attribute was applied to a property? Would GetMethod()
return a MethodBase
instance for that property? Is there a different way of getting the member to which an attribute was applied in C#?
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property,
AllowMultiple = true)]
public class MyCustomAttribute : Attribute
Update: okay, I might have been asking the wrong question. From within a custom attribute class, how do I get the member (or the class containing the member) to which my custom attribute was applied? Aaronaught suggested against walking up the stack to find the class member to which my attribute was applied, but how else would I get this information from within the constructor of my attribute?
© Stack Overflow or respective owner