6

I want to create a bunch of forms that all have the same properties and initialize the properties in the forms constructor by assigning the constructor's parameters.

I tried creating a class that inherits from form and then having all of my forms inherit from that class, but I think since I couldn't call InitializeComponent(), that I was having some problems.

What is some C# code on how to do this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ronnie Overby
  • 45,287
  • 73
  • 267
  • 346

3 Answers3

7

The parent's InitializeComponent should be called by having your constructor call base() like this:

public YourFormName() : base()
{
    // ...
}

(Your parent Form should have a call to InitializeComponent in its constructor. You didn't take that out, did you?)

However, the road you're going down isn't one that will play nicely with the designer, as you aren't going to be able to get it to instantiate your form at design time with those parameters (you'll have to provide a parameterless constructor for it to work). You'll also run into issues where it assigns parent properties for a second time, or assigns them to be different from what you might have wanted if you use your parametered constructor in code.

Stick with just having the properties on the form rather than using a constructor with parameters. For Forms, you'll have yourself a headache.

Adam Robinson
  • 182,639
  • 35
  • 285
  • 343
  • I agree, the designer does not support inheritance well. I had numerous problems with forms / controls that inherited from one another. The designer sometimes would crash, and if you had an error in one of the base classes, I would frequently need to blow away my existing form(s) and revert to a previous version. though it seems elegant, it ended up being far too more trouble than it was worth. – MedicineMan May 05 '09 at 19:24
  • 1
    I may be missing something, but having your constructor call base() like this: public YourFormName() : base() is redundant, and is the default action of C# inheritcance. base() is going to be called implicitly anyway. Otherwise, I agree with the rest of your answer, essentially control inheritance works, but its best to deal with zero-arg constructors in most cases, or make sure your design time constructor (zero-args) has appropriate defaults. – codenheim Apr 05 '14 at 22:59
2

An alternate pattern from inheritance here would be to use a factory to create the forms. This way your factory can set all the properties

JoshBerke
  • 66,142
  • 25
  • 126
  • 164
0

Create an interface and pass that into the constructor of the form.

interface IFormInterface
{
      //Define Properties here
}

public MyForm(IFormInterface AClass)
{
      //Set Properties here using AClass
}

Though I'm usually doing more than just setting properties when I want to do something like this, so I end up creating an abstract class for default behaviors.

JupiterP5
  • 318
  • 1
  • 10