Jason
Jason

Reputation: 3806

Can an attribute discover what method it is applied to at run time?

Is there a way for an attribute that has been applied to a method to know what method it was applied to at run time?

[AttributeUsage(AttributeTargets.Method)]
public class CustomAttribute : Attribute {}

public class Foo
{
    [Custom]
    public void Method() {}
}

Then I query the attribute at run time

var attribute = typeof(Foo)
    .GetMethod("Method")
    .GetCustomAttributes(false)
    .OfType<CustomAttribute>()
    .First();

Can "attribute" tell it was applied to the "Method" method on the "Foo" class?

Upvotes: 2

Views: 183

Answers (2)

user180326
user180326

Reputation:

I believe not, but if it could it would not be helpful.

I'll explain.

Attributes are only created once you query for them. If you just open a dll, none of the attributes that you added will be created. You will first have to get a pointer to the object that the attributes apply to, and then, once you ask for it's attributes, the .net framework will create them for you. So by the time they are instantiated and your code gets to evaluate them you already know what they apply to.

Because of this, I believe it is reccommended to not put too much magic in the attributes themselves.

Upvotes: 5

KeithS
KeithS

Reputation: 71573

Not in a built-in fashion. If an attribute contains method logic that requires knowledge of what it's decorating, the method should take a MemberInfo parameter (or a more derived type like MethodInfo, PropertyInfo, FieldInfo etc.), or an Object if the instance should be passed directly. Then, when invoking the logic on the attribute, it can be given the instance, or the appropriate metadata class, from which it was gotten by the controlling code in the first place.

Upvotes: 0

Related Questions