tags:

views:

1068

answers:

4

How can I apply an Interface to a form class

partial class Form1 : Form, InterfaceA

Is this correct?

Basically I would like to implement an Interface on a form. How To ....

+5  A: 

A Form is just a class (that subclasses System.Windows.Forms.Form), so yes - standard syntax is fine, as you have it.

Edit: As to your partial class part of the question, no, you need only declare that you implement the interface once. From MSDN...

If any of the parts are declared abstract, then the entire type is considered abstract. If any of the parts are declared sealed, then the entire type is considered sealed. If any of the parts declare a base type, then the entire type inherits that class.

Remember, there's no magic in forms or partial classes. C#/.Net is one of the few Microsoft projects that's wizardry free - it really does tend to behave the way you think it should.

Adam Wright
+1  A: 

Yes - a form is just a class at the end of the day

Paul Nearney
Hmmm, except that inheritance doesn't work for visual elements (in Visual Studio) . Because it's done by on teh fly codegeneration not declarative inheritance... This is well-known, the technical reason is well-knowm, but it is not fixed in 2008 and MS don't seem to care. BE WARNED!
kpollock
Except inheritance does work. To access controls on a user control / form from a child, the control must be declared protected or public using the 'Modifiers' in the property editor, or in the .designer.cs file.
configurator
A: 

Because it is a partial class .... .... do I need to also implement the Interface in the designer also (all other parts of the partial class)?

i.e. Form1.Designer.cs

Thanks for the replies.

A: 

When working with partial classes in C#, either:

  • any declaration with the ':' operator must specify exactly the same baseclass and interfaces
  • specifying baseclass and interfaces on one of the declarations will suffice

To make life easier for yourself, add the interface specs in only one place (without checking I suspect this is in the designer class part by default when working with the WinForms designer).