views:

53

answers:

2

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?

A: 

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.

KeithS
I created a second property on the attribute that I set to be the name of the method. Then inside the attribute I do some logic to use the correct property value. Either the one set by the user or the one the code sets. I was hoping to not to have to set the extra property.
Jason
+3  A: 

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.

jdv
In this case I am using the attribute to create a friendly name. I would like it to default to it's full name if one has not been provided. (such as the method name is the friendly name).
Jason