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 check if an object has a property, receiving as input the name of the property to be check.

public static class Extensions
{
    public static bool HasProperty(this object objectToCheck, string propertyName)
    {
        var type = objectToCheck.GetType();
        return type.GetProperty(propertyName) != 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