Getting Object’s All Properties at Runtime
We often need to know a given object’s all properties at run time, for example, tracking a data container object’s properties changes across different components. Here is a simple helper class you can use to do this magic.
|
namespace Helper
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
public static class ObjPropertiesPrinter<objType>
{
public static void OutPut(objType objInstance)
{
Type myObjectType = typeof(objType);
// Get public properties via reflection
System.Reflection.PropertyInfo[] propInfo =
myObjectType.GetProperties();
// Output properties
foreach (System.Reflection.PropertyInfo info in propInfo)
{
Debug.WriteLine(info.Name + ": " + info.GetValue(objInstance, null).ToString());
}
}
}
} |
Once this class is added to your project, it can be used in this way:
|
…
Helper.ObjPropertiesPrinter<MyClass>.OutPut(oneInstanceOfMyClass);
… |
Similarly, you can also get other info via reflection such as fields, events, etc.
Comment Notification
If you would like to receive an email when updates are made to this post, please register here
Subscribe to this post's comments using