How to check whether an object has certain method/property?

175,123

Solution 1

You could write something like that :

public static bool HasMethod(this object objectToCheck, string methodName)
{
    var type = objectToCheck.GetType();
    return type.GetMethod(methodName) != null;
} 

Edit : you can even do an extension method and use it like this

myObject.HasMethod("SomeMethod");

Solution 2

via Reflection

 var property = object.GetType().GetProperty("YourProperty")
 property.SetValue(object,some_value,null);

Similar is for methods

Solution 3

It is an old question, but I just ran into it. Type.GetMethod(string name) will throw an AmbiguousMatchException if there is more than one method with that name, so we better handle that case

public static bool HasMethod(this object objectToCheck, string methodName)
{
    try
    {
        var type = objectToCheck.GetType();
        return type.GetMethod(methodName) != null;
    }
    catch(AmbiguousMatchException)
    {
        // ambiguous means there is more than one result,
        // which means: a method with that name does exist
        return true;
    }
} 

Solution 4

Wouldn't it be better to not use any dynamic types for this, and let your class implement an interface. Then, you can check at runtime wether an object implements that interface, and thus, has the expected method (or property).

public interface IMyInterface
{
   void Somemethod();
}


IMyInterface x = anyObject as IMyInterface;
if( x != null )
{
   x.Somemethod();
}

I think this is the only correct way.

The thing you're referring to is duck-typing, which is useful in scenarios where you already know that the object has the method, but the compiler cannot check for that. This is useful in COM interop scenarios for instance. (check this article)

If you want to combine duck-typing with reflection for instance, then I think you're missing the goal of duck-typing.

Share:
175,123

Related videos on Youtube

Louis Rhys
Author by

Louis Rhys

trying to learn and help others learn :)

Updated on January 07, 2021

Comments

  • Louis Rhys
    Louis Rhys over 3 years

    Using dynamic pattern perhaps? You can call any method/property using the dynamic keyword, right? How to check whether the method exist before calling myDynamicObject.DoStuff(), for example?

    • Cheng Chen
      Cheng Chen about 13 years
      What is the type of myDynamicObject? Is it a class derived from DynamicObject?
    • Louis Rhys
      Louis Rhys about 13 years
      something declared with the dynamic keyword
  • Louis Rhys
    Louis Rhys about 13 years
    GetType() will return the runtime type? (i.e. not object?)
  • Julien
    Julien about 13 years
    yes, GetType() returns the running type whereas typeof() would return object.
  • tzup
    tzup about 13 years
    According to the docs GetType() will return "The exact runtime type of the current instance".
  • Louis Rhys
    Louis Rhys about 13 years
    what if the object can be an object provided by the .NET framework, and I cannot declare it to implement anything?
  • Frederik Gheysels
    Frederik Gheysels about 13 years
    What's the problem ? You can check whether the 'object' is such an object, provided by the .NET framework just in the same way
  • Louis Rhys
    Louis Rhys about 13 years
    for example, you want to check whether there is an "Add" method in an object. ANd the object can be a List<int>, or some other class that's not an IEnumerable
  • Frederik Gheysels
    Frederik Gheysels about 13 years
    So, you have absolutely no idea which class you're using when using a .NET base class ? Can you show some real-life example code ? I think it smells.
  • Fraser
    Fraser about 13 years
    Also, the extension method would need to be static.
  • surfer01
    surfer01 over 12 years
    Perhaps you should take a look at scripting an Adobe product with COM. The same function call can return entirely different COM objects, and by (Adobe's) design, their only common ancestor is object. Also: this is a commonplace pattern in pretty much any modern dynamic scripting language (Python, Javascript, VB script, PHP, Lua... I could go on and on). It's not a bug, it's a feature.
  • efirat
    efirat over 11 years
    I prefer to write: objectToCheck.GetType().GetMethod(methodName) != null
  • HammerIp
    HammerIp over 11 years
    It is a smell but it was created by microsoft. Look at WebControls such as Button, LinkButton, etc. They both implement OnClientClick property but, say, ListControl and Panel do not. OnClientClick is not defined in an interface so reflection is the only option.
  • Zitun
    Zitun over 9 years
    Has explained in the comment after, you can use the new type dynamic : dynamic dynObj = myObject; dynObj.SomeMethod();
  • bovender
    bovender over 7 years
    Extension methods don't work for System.__COMObjects for me; solution for me is to remove the this and use the method without the sugar.
  • Jnr
    Jnr almost 7 years
    Nice. You could also do the GetMethod in a loop to get the appropriate defined property.
  • rr789
    rr789 over 6 years
    I used this to make HasProperty() and HasEvent() methods. Will only find them if Public (and) has {get; set;}. Works well though...
  • Chicowitz
    Chicowitz about 6 years
    Useful for looping through linked lists of UI controls and their Parents
  • Yogesh Patel
    Yogesh Patel about 5 years
    In GetType() there is method like GetProperties(). It is returning array of PropertyInfo. But how can I use GetProperties() method?
  • Nicolas Belley
    Nicolas Belley over 4 years
    the type.GetMethod will throw an exception "ambiguous method" if there is overloads for this method in the targeted class! Beware.
  • HarryTuttle
    HarryTuttle about 3 years
    If you create an extension method on the object type it'll hang off every object that is in scope. That can get noisy. I needed this sort of thing in my test project so put it in a restrictive namespace to hide it from all but the one test class.
  • AminFarajzadeh
    AminFarajzadeh about 2 years
    what about property?
  • user160357
    user160357 about 2 years
    Theatrically* this is the right way for high quality code *...it would be easy to do if the test were hidden in a routine and hard to do if it were a complicated test hard-coded throughout the program. - Code Complete by Steve McConnell