Can C# Attributes access the Target Class?

Viewed 38495

I want to access the properties of a class from the attribute class by using reflection. Is it possible?

For example:

class MyAttribute : Attribute
{
    private void AccessTargetClass()
    {
        // Do some operations
    }
}

[MyAttribute]
class TargetClass
{
}
4 Answers

Not directly, but in order for the attribute to do anything, you already must have a handle to the type/member and call its GetCustomAttributes method, so you can simply pass it in from there:

class MyAttribute : Attribute
{
    public void DoSomethingWithDeclaringType(Type t)
    {
    }
}

Using it like so:

Type classType = typeof(MyClass);
object[] attribs = classType.GetCustomAttributes(typeof(MyAttribute), true);
if(attribs.Length > 0)
{
    ((MyAttribute)attribs[0]).DoSomethingWithDeclaringType(classType);
}

You can acess caller type by using CallerMemberNameAttribute from .NET 4.5:

public CustomAttribute([CallerMemberName] string propertyName = null)
{
    // ...
}

And then use simple reflection

Related