user76071
user76071

Reputation:

Getting attributes for a property where there isn't a direct reference

How do I get attributes of the Stuff property from the DoStuff() method? Is this possible?

public class Bar
{
    public enum FooZ
    {
        Hello,
        GoodBye
    }

    [Display("Hello"]
    public FooZ Stuff { get; set; }

    public Bar() {
        Stuff = FooZ.GoodBye;
    }
}

void Main()
{
    var x = new Bar();

    DoStuff(x.Stuff);
}

void DoStuff(Enum z) {

    // How do I get the DisaplyAttribute from here?
}

Upvotes: 0

Views: 77

Answers (2)

Ani
Ani

Reputation: 113472

You can't. The parameter z doesn't remember where it came from; values don't remember how they were constructed. Remember that in this case, the property is what is decorated with the attribute (meaning that it is embedded in the containing-type's metadata), not the value returned by its getter. You have to reflect the Bar type itself, as in Itay's answer.

Upvotes: 2

Itay Karo
Itay Karo

Reputation: 18296

Type t = typeof(Bar);
PropertyInfo pi = t.GetProperty("Stuff");
Attribute[] att = pi.GetCustomAttributes(typeof(DisplayAttribute), true);

Upvotes: 1

Related Questions