5

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.

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

5 Comments

There's a nice Attributes Tutorial that covers this on MSDN.
@JonSkeet I have one variable called string key and in that value is profile_image, so can I get the value of the key and set it as attribute dynamically?
beacuse my method need a value like attribute=value
@PrashantPimpale: It's not really clear what you're trying to do, I'm afraid. It's probably worth asking in a new question.
@JonSkeet Here is a described question stackoverflow.com/q/53046664/7124761
3

You can try by this way:

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

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

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

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

                foreach (PropertyInfo property in p.GetType().GetProperties())
                {

                   try
                   {
                       Bindable _Attribute = (Bindable)property.GetCustomAttributes(typeof(Bindable), false).First();

                       if (_Attribute.IsBindable)
                       {
                            //TODO
                       }
                    }
                    catch (Exception) { }
                }
            }
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.