Beakie
Beakie

Reputation: 2009

Accessing a property from its attribute

Is it possible to access the type of a property from an attribute that has been implemented on to that property?

public class FooAttribute : Attribute
{
    public string GetPropertyName()
    {
        // return ??
    }
}

public class Bar
{
    [FooAttribute]
    public int Baz { get; set; }
}

I would like GetPropertyName() to return "Baz".

Upvotes: 0

Views: 41

Answers (2)

petelids
petelids

Reputation: 12815

Sriram Sakthivel is correct that this is not possible but if you are using .net 4.5 you can create a workaround using the CallerMemberNameAttribute to pass the caller into the constructor of your attribute, store it and then return it from your GetPropertyName method:

public class FooAttribute : Attribute
{
    public string PropertyName { get; set; }
    public FooAttribute([CallerMemberName] string propertyName = null)
    {
        PropertyName = propertyName;
    }

    public string GetPropertyName()
    {
        return PropertyName;   
    }
}

This will pass the caller (the property) to the constructor of your attribute.

More details on the CallerMemberNameAttribute are available on MSDN.

Upvotes: 1

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73502

What you're asking is not possible. Because Attributes and properties doesn't have "One to One" relationship. You can apply FooAttribute to any number of Properties, In such case which property you need to return from GetPropertyName method?

As I said in comments you can loop through all the types and its properties to see which are all the properties have FooAttribute but obviously that's not what you want.

Upvotes: 1

Related Questions