Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get variable attribute values?

Tags:

c#

attributes

My goal is to get class properties attribute and it's values.

For example, if I have an attribute 'Bindable' to check if property is bindable:

public class Bindable : Attribute
{
    public bool IsBindable { get; set; }
}

And I have a Person class:

public class Person
{
    [Bindable(IsBindable = true)]
    public string FirstName { get; set; }

    [Bindable(IsBindable = false)]
    public string LastName { get; set; } 
}

How can I get FirstName's and LastName's 'Bindable' attribute values?

    public void Bind()
    {
        Person p = new Person();

        if (FirstName property is Bindable)
            p.FirstName = "";
        if (LastName property is Bindable)
            p.LastName = "";
    }

Thanks.

like image 696
Vano Maisuradze Avatar asked Aug 16 '11 14:08

Vano Maisuradze


1 Answers

Instances don't have separate attributes - you have to ask the type for its members (e.g. with Type.GetProperties), and ask those members for their attributes (e.g. PropertyInfo.GetCustomAttributes).

EDIT: As per comments, there's a tutorial on MSDN about attributes.

like image 84
Jon Skeet Avatar answered Oct 11 '22 02:10

Jon Skeet