Prior to C# 3.0, I would typically define a property of a custom user control
with pattern A:
=== PATTERN A ==========
private bool myBool = true;
public bool MyBool {
get { return myBool; }
set { myBool = value; }
}
======================
If this property exists in a custom user control, and I then instantiate
this user control in a WinForm, that property shows up in the visual designer
property pane with the default value I have assigned to the private backing
variable (in the above example, "true"). With the advent of C# 3.0, I want to
switch to the much more terse code in pattern B.
=== PATTERN B ==========
public bool MyBool { get; set; }
======================
Which raises the question of where to set the default. My first attempt was
to say "MyBool = true;" in the constructor of the custom user control. With
this technique, instantiating the control in a WinForm again shows my default
value for this property of the control in the property pane of the visual
designer.
I happened across what I thought was an even cleaner approach in the MSDN
documentation--the DefaultValue attribute so I tried pattern C:
=== PATTERN C ==========
[DefaultValue(true)]
public bool MyBool { get; set; }
======================
This compiles but does not work. That is, the MyBool property for this
control shows "false" in the property pane when instantiated on a WinForm.
(Note that my user control is in a library project and the WinForm is in a
WinForm project, both in the same solution. I first compiled the control
library, then dragged the control from the toolbox onto the WinForm so as to
avoid any stale designer-generated code.)
Should pattern C work? If so, what am I missing?
Environment: VS2008 with target=.NET 2.0 for both projects.