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.

Comments (2)

  1. Anonymous says:

    You could also write a class to do the same that used compiled LINQ expression trees, if you needed to access the values of the properties more frequently, you’d get much, much better performance.

Skip to main content