MiffTheFox
MiffTheFox

Reputation: 21575

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?

Upvotes: 16

Views: 18705

Answers (5)

Jon Barker
Jon Barker

Reputation: 1829

Note that if you call an extension method from a property in class which inherits from a base class that has the extension method applied to it, you have to suffix the extension method with this

e.g.

public int Value
{
    get => this.GetValue<int>(ValueProperty);
    set => SetValue(ValueProperty, value);
}

Where GetValue is my extension method applied to the base class.

Upvotes: 8

Maslow
Maslow

Reputation: 18746

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

Upvotes: 2

Paul van Brenk
Paul van Brenk

Reputation: 7559

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.

Upvotes: 1

ShuggyCoUk
ShuggyCoUk

Reputation: 36486

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

Upvotes: 20

Nate Kohari
Nate Kohari

Reputation: 2224

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.

Upvotes: 8

Related Questions