Limits of Method Extensions in C# (dotNET 3.5)

After spending almost an hour trying to understand why an extended method would just not be available to the extended object types, I found out about a limit of this feature that I will make a note of, for future reference.

This is an example1 of a method extension

that I was trying to use like this (I duly remembered to import the namespace where the extension is declared)

but as it turned out, this is not possible. An extended method can only be applied to instance references of the extended type, and not to the implementation code of the type itself.

In the following code, the extension is applied to a variable that references the Window subclass, and compilation completes successfully.

In order to use the GrabAndMove method in the first case, you must use the extended method as an ordinary static method of WpfWindowEx (which is perfectly legal). So

(1) the example is taken from an application I’m working on at the moment: the idea is to add a method to Window subclasses so as to allow the user to move the windows around the screen by dragging any point, not just the title bar.

Leave a comment

Your email address will not be published. Required fields are marked *