Reputation: 103707
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
}
Upvotes: 2
Views: 110
Reputation: 1064234
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
.
Upvotes: 2
Reputation: 11367
Yes, you could use
foreach (var objProperty in o.GetType().GetProperties())
{
Console.WriteLine(objProperty.Name + ": " + objProperty.GetValue(o, null));
}
Upvotes: 1
Reputation: 755587
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.
Upvotes: 4