System.Reflection

I’ve been wondering how to do stuff in C# similar to $$i from my PHP days – i.e. dynamically calling properties on an object, when I do not know their names at compile time.

Example code

using System;
using System.Reflection;
using System.Windows.Forms;
namespace ReflectionExample
{
    public class ReflectionExample
    {
        public virtual void ShowObjectProperties(object exampleObject)
        {
            PropertyInfo[] properties = exampleObject.GetType().GetProperties();
            foreach (PropertyInfo property in properties)
            {
                object resultProperty = exampleObject.GetType().GetProperty(property.Name).GetValue(exampleObject, null);
                if (resultProperty != null)
                {
                    MessageBox.Show(string.Format("{0} has a value of: {1}", property.Name, resultProperty.ToString()));
                }
            }
        }
    }
}

There is obviously lots more to the reflection namespace than this – the above example is the first time I’ve really used it though.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>