Reflection is a method by which we can use metadata at runtime to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. It has many uses, ranging from allowing usage of attributes to creating instances of dynamically generated classes and using them. You can even use reflection to read and modify private member variables of an object. Today, we're going to look at a very simple example which will allow us to read the value of a public property given an instance.

The Class

Let's take a very simple class:

   
    
namespace MyNamespace    
{    
    public class MyClass    
    {    
        public int MyProperty { get; set; }    
    }    
}    
    

Note, that I've put it in a separate namespace to show that it's easy to deal with this when using reflection.

The Runner

We'll run everything in a very simple console application:

   
    
public class Program    
{    
    static void Main(string[] args)    
    {    
        new Program().Run();    
    }    
    
    private void Run()    
    {    
        MyClass o = new MyClass { MyProperty = 25 };    
        object value = GetPropertyValue(o, "MyProperty");    
        Console.WriteLine(value);    
    }    
}    
    

We're basically creating an instance of MyClass and passing the instance and the string "MyProperty" to a method called GetProperty. The method is returning an object (which we could have cast to anything we needed). We're passing the returned object to Console.WriteLine.

The Method

This is where we use reflection to find the value of the "MyProperty" property given an instance. Add the following method to the class:

   
    
private object GetPropertyValue(object o, string propertyName)    
{    
    Type type = o.GetType();    
    PropertyInfo info = type.GetProperty(propertyName);    
    object value = info.GetValue(o, null);    
    return value;    
}    
    

We're getting the type information by calling GetType() on the object. Next, we call GetProperty() on the type information. Note, this only gives us information about the property and not the property itself. We then have to call GetValue() on the property information passing in the instance from which to get the actual value.

And that's all it takes :)

PS: You'll need a reference to System.Reflection to use Reflection.

PPS: Yes, this is a very very simple example of using reflection, but I found quite a few questions over at the forums today that would be answered by this. We all have to start somewhere, right?