Welcome to MSDN Blogs Sign in | Join | Help

Bill Li

Think globally, act locally.

Syndication

News

These postings are provided "AS IS" with no warranties, and confers no rights.


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.

Published Thursday, November 20, 2008 10:19 PM by Bali

Filed under:

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 RSS

Comments

# infoblog &raquo; Getting Object???s All Properties at Runtime @ Thursday, November 20, 2008 9:33 AM

PingBack from http://blog.a-foton.ru/index.php/2008/11/20/getting-object%e2%80%99s-all-properties-at-runtime/

infoblog &raquo; Getting Object???s All Properties at Runtime

# re: Getting Object’s All Properties at Runtime @ Thursday, November 20, 2008 1:05 PM

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.

Ankiro

Leave a Comment

(required) 
required 
(required) 
Page view tracker