How to get properties of an object

  • Thread starter Thread starter John
  • Start date Start date
Following queries the available properties, then loops over them,
printing the name and value of each:

foreach(PropertyDescriptor prop in
TypeDescriptor.GetProperties(obj)) {
Console.WriteLine("{0}\t{1}", prop.Name,
prop.GetValue(obj));
}

Marc
 
What is one of the property is itself composite and has multiple sub
properties so to speak?

Regards
 
Rinse, repeat... i.e. the same again, for the value returned from:
object innerValue = prop.GetValue(obj);

Note that there is a chance that innerValue could be null; in this
case, you can use:

PropertyDescriptorCollection innerProps =
TypeDescriptor.GetProperties(prop.PropertyType);

This will give you the properties associated with the Type matching
the property - one minor caveat: if the value implements
ICustomTypeDescriptor, then it won't have chance to speak for itself,
since this only works on instances. From 2.0, the preferred approach
for custom properties is TypeDescriptionProvider, which works on both
the Type and an instance.

Marc
 
Back
Top