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 method, receiving as input the name of the methodto be check.

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