3

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.

Community
  • 1
  • 1
Steve
  • 506
  • 6
  • 16
  • @SteveWellens: Wrong; for explicit interface implementations, you do. – SLaks Feb 07 '12 at 23:28
  • @SLaks: This isn't an explicit interface implementation, but it is a cross-cast, which also needs an explicit cast. – Ben Voigt Feb 07 '12 at 23:30
  • Good to know that's a cross-cast. I knew it couldn't be an actual explicit implementation since I wasn't actually inheriting from the interface in my base class. – Steve Feb 08 '12 at 00:08
  • 1
    @wlblakeshaw: Explicit interface implementation is when your methods are private and named `IMyFormInterface.SomeMethod`, instead of public and named `SomeMethod`. – Ben Voigt Feb 08 '12 at 01:02

2 Answers2

4

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.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • I'll look into the UserControl method. Still pretty new to this, but makes sense. Thanks! – Steve Feb 08 '12 at 00:06
0

I had the same problem with a base control.
Because Designer does not like abstract base control classes I refactored the abstract methods to virtual methods that throw a NotImplementedException.
I don't know which way is the best.

brgerner
  • 4,287
  • 4
  • 23
  • 38
  • I was originally doing that as well. But I wasn't totally satisfied with that approach. I kept tinkering with things until I eventually arrived at my solution above. – Steve Feb 08 '12 at 14:45