We have a lot of confortable methods ready to use in our .NET objects and this is wonderful: just think for example the method .toString()! How much do we use it? But, sometimes, these methods aren’t enough and we need to create others on our own.

In this post I show how to create an extesion method useful to get the value of an property of a generic object starting from the name of the property.

public static class Extensions
{
    public static object GetPropertyValue(this object o, string propertyName)
    {
        return o.GetType().GetProperties()
            .Single(pi => pi.Name == propertyName)
            .GetValue(o, null);
    }
}

Note:

  1. The class has to be static (or shared in VB.NET)
  2. Also the method has to be static (or shared in VB.NET)
Advertisements