Sarath Subramanian
Sarath Subramanian

Reputation: 21401

Get all properties of Browsable attribute

I have a class which have many properties and some properties have Browsable attribute.

public class MyClass
{
    public int Id;
    public string Name;
    public string City;

    public int prpId
    {
        get { return Id; }
        set { Id = value; }
    }

    [Browsable(false)]
    public string prpName
    {
        get { return Name; }
        set { Name = value; }
    }

    [Browsable(true)]
    public string prpCity
    {
        get { return City; }
        set { City= value; }
    }
}

Now using Reflection, how can I filter the properties which have Browsable attributes? In this case I need to get prpName and prpCity only.

Here is the code I have tried so far.

 List<PropertyInfo> pInfo = typeof(MyClass).GetProperties().ToList();

but this selects all the properties. Is there any way to filter properties which have Browsable attributes only?

Upvotes: 1

Views: 3643

Answers (2)

Dejan
Dejan

Reputation: 10373

To include only members having [Browsable(true)], you can use:

typeof(MyClass).GetProperties()
               .Where(pi => pi.GetCustomAttributes<BrowsableAttribute>().Contains(BrowsableAttribute.Yes))
               .ToList();

Upvotes: 4

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101731

You can use Attribute.IsDefined method to check if Browsable attribute is defined in property:

typeof(MyClass).GetProperties()
               .Where(pi => Attribute.IsDefined(pi, typeof(BrowsableAttribute)))
               .ToList();

Upvotes: 1

Related Questions