Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Adding extension methods to a base class so that they appear in derived classes

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?

like image 711
MiffTheFox Avatar asked Aug 01 '09 22:08

MiffTheFox


2 Answers

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).

like image 127
ShuggyCoUk Avatar answered Sep 28 '22 08:09

ShuggyCoUk


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.

like image 39
Nate Kohari Avatar answered Sep 28 '22 10:09

Nate Kohari