views:

1474

answers:

7

Call me crazy, but I'm the type of guy that likes constructors with parameters (if needed), as opposed to a constructor with no parameters followed by setting properties. My thought process: if the properties are required to actually construct the object, they should go in the constructor. I get two advantages:

  1. I know that when an object is constructed (without error/exception), my object is good.
  2. It helps avoid forgetting to set a certain property.

This mindset is starting to hurt me in regards to form/usercontrol development. Imagine this UserControl:

public partial class MyUserControl : UserControl
{
    public MyUserControl(int parm1, string parm2)
    {
        // We'll do something with the parms, I promise
        InitializeComponent();
    }
}

In designtime, if I drop this UserControl on a form, I get an exception:

Failed to create component 'MyUserControl' ...
System.MissingMethodException - No parameterless constructor defined for this object.

It seems like, to me, the only way around that was to add the default constructor (unless someone else knows a way).

public partial class MyUserControl : UserControl
{
    public MyUserControl()
    {
        InitializeComponent();
    }

    public MyUserControl(int parm1, string parm2)
    {
        // We'll do something with the parms, I promise
        InitializeComponent();
    }
}

The whole point of not including the parameterless constructor was to avoid using it. And I can't even use the DesignMode property to do something like:

public partial class MyUserControl : UserControl
{
    public MyUserControl()
    {
        if (this.DesignMode)
        {
            InitializeComponent();
            return;
        }

        throw new Exception("Use constructor with parameters");
    }
}

This doesn't work either:

if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)

Fine, moving along ...

I have my parameterless constructor, I can drop it on the form, and the form's InitializeComponent will look like this:

private void InitializeComponent()
{
    this.myControl1 = new MyControl();

    // blah, blah
}

And trust me, because I did it (yes, ignoring the comments Visual Studio generated), I tried messing around and I passed parameters to InitializeComponent so that I could pass them to the constructor of MyControl.

Which leads me to this:

public MyForm()
{
    InitializeComponent(); // Constructed once with no parameters
    this.myControl1 = new MyControl(anInt, aString);  // Constructed a 2nd time, what I really want
}

For me to use a UserControl with parameters to the constructor, I have to add a 2nd constructor that I don't need? And instantiate the control twice?

I feel like I must be doing something wrong. Thoughts? Opinions? Assurance (hopefully)?

+2  A: 

Provide a parameterless constructor for the designer and make it private - if you really must do it this way... :-)

EDIT: Well of course this won't work for UserControls. I obviously wasn't thinking clearly. The designer need to execute the code in InitializeComponent() and it's can't work if the constructor is private. Sorry about that. It does work for forms, however.

danbystrom
That was actually the first thing I did, but I'm pretty sure that doesn't work. You'll get the same 'parameterless constructor' error when dropping it on the form.
JustLooking
If it is private, I doubt that the designer can use it.
Fredrik Mörk
Really? I always make the constructor of my *dialogs* private... and that works, at least.
danbystrom
UserControl's don't work - this also has significant issues if you're using multiple assemblies.
Reed Copsey
Are you sure they are `private`? If you make a constructor private, only the code within the class can use it. If you make them `internal` all code in the same assembly can use them, but no code outside the assembly (unless you use the `InternalsVisibleTo` attribute). For the VS designers to be able to use them, they need to be `public`.
Fredrik Mörk
I'm pretty sure! :-) That's a design idiom I've been using for several years now. The designer seems to be using reflection.
danbystrom
Yes, that might be. Reflection does not let itself be stopped by such details as accessibility of members...
Fredrik Mörk
Private constructors for modal dialog boxes (forms) is a great way to make sure that a consumer of a dialog doesn't forget to dispose it (or even have to create it for that matter). Use a public static method on the form and be happy!
danbystrom
+3  A: 

This is unfortunately a design issue that will occur frequently, not just in the control space.

There are often situations where you need to have a parameterless constructor, even though a parameterless constructor is not ideal. For example, many value types, IMO, would be better off without parameterless constructors, but it's impossible to create one that works that way.

In these situations, you have to just design the control/component in the best manner possible. Using reasonable (and preferably the most common) default parameters can help dramatically, since you can at least (hopefully) initialize the component with a good value.

Also, try to design the component in a way that you can change these properties after the component is generated. With Windows Forms components, this is typically fine, since you can pretty much do anything until load time safely.

Again, I agree - this isn't ideal, but it's just something we have to live with and work around.

Reed Copsey
+1  A: 

Just do this:

public partial class MyUserControl : UserControl
{
    public MyUserControl() : this(-1, string.Empty)
    {
    }

    public MyUserControl(int parm1, string parm2)
    {
        // We'll do something with the parms, I promise
        if (parm1 == -1) { ... }
        InitializeComponent();
    }
}

Then the 'real' constructor can act accordingly.

Bob Nadler
I admit it, I'm not sure what this buys me (or how it answers my question).
JustLooking
It was the duplicate InitializeComponent() calls that caught my eye. Also, a private parameterless constructor with a UserControl works with the VS designer for me.
Bob Nadler
Well what you can do with this is show in the designer a message like "parameter foo needs setting for runtime". To indicate the need to setup the parameters you would normally pass in using a constructor. The setting of the parameter may need to handle some of the controls setup which would usually be done in the constructor.
PeteT
+2  A: 

Well, in short, the designer is the kind of guy that likes parameter-less constructors. So, to the best of my knowledge, if you really want to use parameter based constructors you are probably stuck with working around it one way or the other.

Fredrik Mörk
"The designer is the kind of guy" ... good stuff (funny)! Yeah, it looks like I'll have to utilize work-arounds. I just wanted to make sure that there wasn't some slick way of doing things, or there's some "known rule" such as: "You never do what I was doing with my UserControl"
JustLooking
+1  A: 

I would recommend

public partial class MyUserControl : UserControl
{
    private int _parm1;
    private string _parm2;

    private MyUserControl()
    {
        InitializeComponent();
    }

    public MyUserControl(int parm1, string parm2) : this()
    {
        _parm1 = parm1;
     _parm2 = parm2;
    }
}

As this way the base constructor is always called first and any references to components are valid.

You could then overload the public ctor if need be, ensuring the control is always instantiated with the correct values.

Either way, you ensure that the parameterless ctor is never called.

I haven't tested this so if it falls over I apologise!

Antony Koch
If my memory serves me, because of the private "parameterless" constructor, I still couldn't use this in design mode. But, +1 anyway.
JustLooking
+5  A: 

Design decisions made regarding the way Windows Forms works more or less preclude parameterized .ctors for windows forms components. You can use them, but when you do you're stepping outside the generally approved mechanisms. Rather, Windows Forms prefers initialization of values via properties. This is a valid design technique, if not widely used.

This has some benefits, though.

  1. Ease of use for clients. Client code doesn't need to track down a bunch of data, it can immediately create something and just see it with sensible (if uninteresting) results.
  2. Ease of use for the designer. Designer code is clearer and easier to parse in general.
  3. Discourages unusual data dependencies within a single component. (Though even microsoft blew this one with the SplitContainer)

There's a lot of support in forms for working properly with the designer in this technique also. Things like DefaultValueAttribute, DesignerSerializationVisibilityAttribute, and BrowsableAttribute give you the opportunity to provide a rich client experience with minimal effort.

(This isn't the only compromise that was made for client experience in windows forms. Abstract base class components can get hairy too.)

I'd suggest sticking with a parameterless constructor and working within the windows forms design principles. If there are real preconditions that your UserControl must enforce, encapsulate them in another class and then assign an instance of that class to your control via a property. This will give a bit better separation of concern as well.

Greg D
+1, thanks a lot for the help.
JustLooking
+9  A: 

There are two competing paradigms for designing classes:

  1. Use parameterless constructors and set a bunch of properties afterwards
  2. Use parameterized constructors to set properties in the constructor

The Visual Studio Windows Forms Designer forces you to provide a parameterless constuctor on controls in order to work properly. Actually, it only requires a parameterless constructor in order to instantiate controls, but not to design them (the designer will actually parse the InitializeComponent method while designing a control). This means that you can use the designer to design a form or user control without a parameterless constructor, but you cannot design another control to use that control because the designer will fail to instantiate it.

If you don't intend to programmatically instantiate your controls (i.e. build your UI "by hand"), then don't worry about creating parameterized constructors, since they won't be used. Even if you are going to programmatically instantiate your controls, you may want to provide a parameterless constructor so they can still be used in the designer if need be.

Regardless of which paradigm you use, it is also generally a good idea to put lengthy initialization code in the OnLoad() method, especially since the DesignMode property will work at load time, but not work in the constructor.

CodeSavvyGeek
+1 for mentioning DesignMode in OnLoad().
Greg D
+1 for a very good answer. I think it is similar to Greg D's answer, so I'll give him the 'accepted answer' (only because he posted first). I want to give you both the green checkmark.
JustLooking