views:

53

answers:

2

If our UserControl requires certain properties are set for it to be useful, what's the best way to ensure they are set? Even if just as a note to self and/or close colleagues.

We've tried using an Initialize method, but that's already caught us out because we forgot to update the Initialize in one instance, having slightly changed the design.

The other idea is to use a sensible default, so that if we forget to set it then there's at least something useful there. But in this case there isn't a useful default. I really want a strong note to self to remind me there's something here that needs to be set every time I create an instance of the control.

+2  A: 

Nothing screams Must Be Implemented like an Exception. If there's a property that has critical importance, I always just make sure I know about it when it comes to running the code:

public object ImportantProperty 
{
    get
    {
        if (!this.DesignMode && _superImportantProperty == null)
        {
            throw new Exception("The property ImportantProperty must be set.");
        }
    }
}

Of course, this could be a bit extreme if you could get away with a default property value. Always choose a graceful course of action over a catastrophic course of action when possible.

GenericTypeTea
+3  A: 

Nothing you could enforce at the designer level, there is no "I'm done designing" trigger. But certainly at runtime, just throw an exception at the earliest possible moment:

protected override void OnCreateControl(EventArgs e) {
    if (!DesignMode && !mumbleAssigned) 
        throw new InvalidOperationException("Oops, Mumble property wasn't set");
    base.OnCreateControl(e);
}

You could make it more subtle if you implement the OnPaint() method. And simply e.Graphics.DrawText a reminder. Call Invalidate() in the property setter. This works at design time.

Hans Passant