Today Hadley pointed out some non-intuitive behaviour of the DefaultValueAttribute. Actually after you work out how Visual Studio interprets this attribute it does make sense but initially the logic appears to be flawed. Ok, so what am I talking about? Well say you have a custom control and you have a property defined as the following:
private mTitle as String
<System.ComponentModel.DefaultValue(“Hello World”)> _
Public Property Title as String
Get
Return mTitle
End Get
Set (ByVal value as String)
mTitle=value
End Set
End Property
When you drop this control onto a form the Title property will appear in the property grid and you can specify the value that will be assigned to the property in the designer file, eg:
UserControl1.Title=”Blah”
Now the weird thing is that when you look at the property grid the value appears to be set to nothing or an empty string, but surely we set the default value in the attribute? wrong, what we set in the attribute is what the designer uses to check whether what you have typed is equal to the default value. For example if I typed “Hello World” into the property grid it would remove the UserControl1.Title=xxxxx line from the designer file. This attribute assumes that somewhere along the line you, as the developer, will have set the default value, eg:
private mTitle as String = “Hello World”
<System.ComponentModel.DefaultValue(“Hello World”)> _
Public Property Title as String
Get
Return mTitle
End Get
Set (ByVal value as String)
mTitle=value
End Set
End Property