Search code examples
c#.netreflectiontypedescriptor

Filter properties returned by TypeDescriptor.GetProperties() depending on the class they are declared in


Hey guys. I have the following situation.

I want to use a TypeDescriptor to get the properties of a certain type. The type's depth in the inheritance hierarchy may vary. I only want to get the properties declared in the type itself and not in its parents (base). The problem is that when I call TypeDescriptor.GetProperties() it would return everything declared up the inheritance hierarchy up to Object.

I only saw that I can filter the output by Attributes, but I don't want to add another attribute to the properties in my types just for this. Getting them through reflection and not using TypeDescriptor would do what I want, but is not an option for me, because some of the properties will be added dynamically to the type at some point.

Any ideas? If the question is not clear I could provide an example.


Solution

  • You can filter the properties using the ComponentType property :

    var properties = from p in TypeDescriptor.GetProperties(x).Cast<PropertyDescriptor>()
                     where p.ComponentType == x.GetType()
                     select p;