Reflection can come in handy in some situations.

Some of the situations in which I really like reflection is when you have to read properties when you only have the property name.
For instance when mapping data from xml to strongly typed objects and vice versa.

public T ReadProperty<T>(object model, string propertyName)
{
     Assert.IsNotNull(model, "model");
     Assert.IsNotNull(propertyName, "propertyName");

     var result = default(T);
     PropertyInfo property = model.GetType().GetProperties().FirstOrDefault(p => p.Name == propertyName);
     if (property != null)
     {
         var propertyResult = property.GetValue(model, null);
         if (propertyResult is T)
         {
             result = (T) propertyResult;
         }
         else
         {
             Logging.Info(string.Format("{0}: Property {1} is not of type {2}", typeof(PropertyReader), propertyName, typeof(T)));
         }
     }
     else
     {
         Logging.Info(string.Format("{0}: Property {1} not found in type {2}", typeof(PropertyReader), propertyName, model.GetType()));
     }
     return result;
}

This method reads a property from an object and returns the data in the type provided by the generic type.

This is just one of the few situations in which reflection is very powerful.

The following two tabs change content below.
I'm a software developer from Utrecht. Interested in DDD, continuous delivery, new technologies & frameworks.

Latest posts by Vincent Keizer (see all)