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

C#.NetMethodsReflectionProperties

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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 - C#

via Reflection

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

Similar is for methods

Solution 3 - C#

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 - C#

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.

Solution 5 - C#

To avoid AmbiguousMatchException, I would rather say

objectToCheck.GetType().GetMethods().Count(m => m.Name == method) > 0

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLouis RhysView Question on Stackoverflow
Solution 1 - C#JulienView Answer on Stackoverflow
Solution 2 - C#StecyaView Answer on Stackoverflow
Solution 3 - C#esskarView Answer on Stackoverflow
Solution 4 - C#Frederik GheyselsView Answer on Stackoverflow
Solution 5 - C#AlexanderView Answer on Stackoverflow