Method that iterates over the properties of passed objects

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

Is this possible using reflection?

eg.

public void OutputProperties(object o)
{

      // loop through all properties and output the values

}

      

+2


source to share


3 answers


Try to run

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);
  }
}

      



All properties declared for a particular type will be displayed here. It will fail if any of the properties throws an exception on evaluation.

+4


source


An alternative using TypeDescriptor

, allowing custom object models to show flexible properties at runtime (what you see can be larger than what is in the class and can use custom type converters to convert strings):

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 other interesting patterns are possible with ICustomTypeDescriptor

and TypeDescriptionProvider

.

+2


source


Yes, you could use

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

      

+1


source







All Articles