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
.