Method that iterates over the properties of passed objects
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 to share
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 to share