It is possible, although you have to be careful with the parameters on overloads - it's usually a good idea to avoid object
types as that often causes confusing code. You can fall foul of the funny way C# picks overloads. It will choose a 'closer' match with types that can be implicitly cast to over a 'further' one that has exact matches (see this question).
Button myButton = // get button
Window currentWindow = // get window
// which method is called here?
currentWindow.Display( myButton );
You want your code to be fairly clear, especially when returning to this code in a year or so, what overload is being called.
Extension methods provide a really elegant way to expand the functionality of objects. You can add behaviour that it didn't have originally. You have to be careful with them though, as they're very prone to creating confusing code. It's best practice to avoid method names already used, even if they are clear overloads, as they don't show up after the class in intellisense.
Here the problem appears to be that the extension method can implicitly convert your button to an object, and so picks itself as the best match, instead of the actual display method. You can explicitly call the extension method as a normal static call, but you can't force it to call the underlying class's method.
I would change the name of the extension method:
object somethingToMakeIntoAButton = // get object
Window currentWindow = // get window
// which method is called here?
currentWindow.DisplayButton( somethingToMakeIntoAButton );
Then...
class WindowExtensions
{
public void DisplayButton(this Window window, object o)
{
Button button = BlahBlah(o);
// now it's clear to the C# compiler and human readers
// that you want the instance method
window.Display(button);
}
}
Alternatively if the second parameter on the extension method was a type that couldn't be implicitly converted to from Button
(say int
or string
) this confusion wouldn't happen either.