Find all properties without BrowsableAttribute explicitely set to Yes in .Net

174 views Asked by At

Is there a way to find all the properties of a given type without the BrowsableAttribute explicitly set to Yes in .Net?

I've tried the following code without success (all the properties which are browsable by default are also returned):

PropertyDescriptorCollection browsableProperties = TypeDescriptor.GetProperties(type, new Attribute[] { BrowsableAttribute.Yes });
1

There are 1 answers

10
Sriram Sakthivel On BEST ANSWER

A bit of reflection and linq will help here.

var result =  type
    .GetProperties()
    .Where(x =>
            x.GetCustomAttribute<BrowsableAttribute>() == null ||
            !x.GetCustomAttribute<BrowsableAttribute>().Browsable)
    .ToList();

You can introduce a local variable to avoid calling GetCustomAttribute method twice.

If you're in .Net framework version less than 4.5 you can write your own GetCustomAttribute extension method like this

public static T GetCustomAttribute<T>(this MemberInfo element) where T: Attribute
{
    return (T) element.GetCustomAttribute(typeof(T));
}