views:

822

answers:

4

I currently have an extension method on System.Windows.Forms.Control like this:

public static void ExampleMethod(this Control ctrl){ /* ... */ }

However, this method doesn't appear on classes derived from Control, such as PictureBox. Can I make an extension method that appears not only in Control, but for classes derived from Control, without having to do an explicit cast?

+7  A: 

An extension method will actually apply to all inheritors/implementors of the type that's being extended (in this case, Control). You might try checking your using statements to ensure the namespace that the extension method is in is being referenced where you're trying to call it.

Nate Kohari
+5  A: 

You must include the using statement for the namespace in which your extensions class is defined or the extension methods will not be in scope.

Extension methods work fine on derived types (e.g. the extension methods defined on IEnumerable<T> in System.Linq).

ShuggyCoUk
Thank you! It was defined in a different namespace, adding a using statement fixed it.
MiffTheFox
A: 

I think you have to make the extension generic:

public static void ExampleMethod<T>(this T ctrl)
    where T : Control 
{ /* ... */ }

No, you don't have to.. it should also work with the non-generic version you posted, remember to add the namespace for your extensions.

pb
A: 

You can also make sure your extensions aren't defined in a namespace, then any project that references them will auto-import them.

Maslow