I have public object LastControl which will contain custom classes, some of which have Resize() method. I want to know how to find out if current value is of a class that has this method and in that case run it.
As of now, I get errors when trying to compile LastControl.Resize() because the type object itself doesn’t have that method. Casting as control class could be an easy solution, but there are multiple classes, so I don’t know what to do here. I figured I should start with using GetType in some way.
The reflection-based way, as you alluded to by
GetType, uses theGetMethodmethod. You can use it to get aMethodInfoinstance on which you can then call theInvokemethod to execute the method.A cleaner way, however, would be to declare an interface that provides a
Resize()method:In any custom class of yours that has a
Resize()method, you could implement that interface. Then, for checking whether the current value ofLastControlhas aResize()method, you try to cast the object by usingas, and if the result is notnull, you can safely call theResize()method: