While having fun with reflection in C#, I started to wonder when I should use TypeDescriptor.GetProperties() vs Type.GetProperties().
The difference is in what they return. obj.GetType().GetProperties()
returns a System.Reflection.PropertyInfo[] whereas TypeDescriptor.GetProperties() returns a
. The PropertyDescriptorCollection
,PropertyInfo
class represents only actual properties created on the object. A PropertyDescriptor
is either a custom concrete child of the PropertyDescriptor
class (implemented by the type defining the custom descriptor), or is an instance of ReflectPropertyDescriptor
that uses the PropertyInfo
class to provide dynamic invocation of the property.
So for a class that does not define a custom descriptor, you will functionally get the same objects back, though the PropertyDescriptor
is abstracting away the PropertyInfo
.
Where is this useful?
The TypeDescriptor
class is used in designers, so that they can interact with the design-time environment. In particular, designers can override and extend various features of TypeDescriptor
, but not Type
.
One good example is working with data-bound controls. The DataSource
property is of type System.Object
, yet at design-time, that property is replaced with a new property that has a richer design-time UI.