How to check whether an object has certain method/property?
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.
Related videos on Youtube
Comments
-
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 about 13 yearsWhat is the type of myDynamicObject? Is it a class derived from
DynamicObject
? -
Louis Rhys about 13 yearssomething declared with the dynamic keyword
-
-
Louis Rhys about 13 yearsGetType() will return the runtime type? (i.e. not object?)
-
Julien about 13 yearsyes, GetType() returns the running type whereas typeof() would return object.
-
tzup about 13 yearsAccording to the docs GetType() will return "The exact runtime type of the current instance".
-
Louis Rhys about 13 yearswhat if the object can be an object provided by the .NET framework, and I cannot declare it to implement anything?
-
Frederik Gheysels about 13 yearsWhat'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 about 13 yearsfor 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 about 13 yearsSo, 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 about 13 yearsAlso, the extension method would need to be static.
-
surfer01 over 12 yearsPerhaps 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 over 11 yearsI prefer to write: objectToCheck.GetType().GetMethod(methodName) != null
-
HammerIp over 11 yearsIt 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 over 9 yearsHas explained in the comment after, you can use the new type dynamic : dynamic dynObj = myObject; dynObj.SomeMethod();
-
bovender over 7 yearsExtension methods don't work for
System.__COMObject
s for me; solution for me is to remove thethis
and use the method without the sugar. -
Jnr almost 7 yearsNice. You could also do the GetMethod in a loop to get the appropriate defined property.
-
rr789 over 6 yearsI used this to make HasProperty() and HasEvent() methods. Will only find them if Public (and) has {get; set;}. Works well though...
-
Chicowitz about 6 yearsUseful for looping through linked lists of UI controls and their Parents
-
Yogesh Patel about 5 yearsIn
GetType()
there is method likeGetProperties()
. It is returning array ofPropertyInfo
. But how can I useGetProperties()
method? -
Nicolas Belley over 4 yearsthe type.GetMethod will throw an exception "ambiguous method" if there is overloads for this method in the targeted class! Beware.
-
HarryTuttle about 3 yearsIf 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 about 2 yearswhat about property?
-
user160357 about 2 yearsTheatrically* 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