tags:

views:

47

answers:

3

Trying to figure out how to create a method that will iterate over the properties of an object, and output them (say console.writeline for now).

Is this possible using reflection?

e.g.

public void OutputProperties(object o)
{

      // loop through all properties and output the values

}
+4  A: 

Try the following

public void OutputProperties(object o) {
  if ( o == null ) { throw new ArgumentNullException(); }
  foreach ( var prop in o.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) ) {
    var value = prop.GetValue(o,null);
    Console.WriteLine("{0}={1}", prop.Name, value);
  }
}

This will output all properties declared on the specific type. It will fail if any of the properties throw an exception when evaluated.

JaredPar
+1  A: 

Yes, you could use

foreach (var objProperty in o.GetType().GetProperties())
{
    Console.WriteLine(objProperty.Name + ": " + objProperty.GetValue(o, null));
}
Maximilian Mayerl
+2  A: 

An alternative using TypeDescriptor, allowing custom object models to show flexible properties at runtime (i.e. what you see can be more than just what is on the class, and can use custom type-converters to do the string conversion):

public static void OutputProperties(object obj)
{
    if (obj == null) throw new ArgumentNullException("obj");
    foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(obj))
    {
        object val = prop.GetValue(obj);
        string s = prop.Converter.ConvertToString(val);
        Console.WriteLine(prop.Name + ": " + s);
    }
}

Note that reflection is the default implementation - but many other more interesting models are possible, via ICustomTypeDescriptor and TypeDescriptionProvider.

Marc Gravell
internally aren't they using reflection?
mrblah