C# – When a user control has Browsable false on public property, why does designer set it to null when added to a form

c++user-controlsvisual-studio-2008winforms

I have a user control that has a few public properties, one is an object where I set [Browseable(false)]. When I add this control in Visual Studio's designer the generated code sets this object to null.

public class Foo : System.Windows.Forms.UserControl
{
    [Browsable(false)]
    public object Bar { get; set; }

    [Browsable(true)]
    public bool IsSomething { get; set; }

    ...
}

private void InitializeComponent()
{
    ...
    this.foo = new Foo();

    this.foo.IsSomething = false;
    this.foo.Bar = null;
    ...
}

I don't understand why Visual Studio would want to do that and I'm curious if there is a way to mark it so that it doesn't set it. I discovered this by setting the object to something in the constructor only to watch the contol's parent set it back to null.

Best Solution

There are a couple of options here. First, BrowsableAttribute only determines whether the property shows up in the property grid. To prevent the property from being serialized at all, use the DesignerSerializationVisibilityAttribute:

[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public object Bar { get; set; }

Second, if you want the property to be serialized, but only when the user has actually changed the value, use the DefaultValueAttribute:

[Browsable(true)]
[DefaultValue(false)]
public bool IsSomething { get; set; }

This will cause the property to only be serialized if it is different from its default value. This also has other positive side-effects

  1. The property value is shown in a normal font when it has not been changed, but in bold when it has been changed.
  2. The "Reset" option will be available when right-clicking the property in the property grid.

There are more advanced techniques for controlling property interaction with the designer (Google "ShouldSerialize"), but these attributes should get you most of the way there.

Related Question