Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Form inheritance

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?

like image 219
Ronnie Overby Avatar asked May 05 '09 19:05

Ronnie Overby


2 Answers

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.

like image 79
Adam Robinson Avatar answered Oct 02 '22 05:10

Adam Robinson


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

like image 24
JoshBerke Avatar answered Oct 02 '22 06:10

JoshBerke