Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly call interface methods from a winforms base class

I have a winforms baseform that contain calls to certain methods that need to be implemented in derived forms. I want to ensure that my derived forms do indeed implement those methods with as much compile time support as possible. We all know the problem of not being able to define a winforms class as abstract if you want to be able to use the designer (see this question).

I created an Interface that contains the method signatures that need to be implemented in a derived form. I then call the Interface methods directly from the base class like such:

((IMyFormInterface)this).SomeInterfaceMethod();

(Note that my base class does not inherit IMyFormInterface. If it did, then derived classes wouldn't be forced to implement it.)

And then I inherit from the Interface in my derived form (which the compiler forces me to implement):

public partial class TestForm : BaseForm, IMyFormInterface

The only thing I (or other users) have to remember is to inherit IMyFormInterface.

Is it acceptable to call interface methods directly like this? My goal in all of this is to be able to get as close as possible to ensuring derived forms implement these "abstract" form methods at compile time, not run time.

like image 564
Steve Avatar asked Mar 24 '26 00:03

Steve


1 Answers

That's one way to work around the designer restriction. Another would be to use the designer to build a UserControl, and then let your form base class be abstract and instantiate the control docked to the full client area.

If you use this approach, I'd assert (this is IMyFormInterface) in your constructor to catch that error as early as possible.

like image 93
Ben Voigt Avatar answered Mar 26 '26 13:03

Ben Voigt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!