Control.DefaultValue isn't.

Tags: .NET

Here is a common source of confusion and frustration that's been experienced by most people developing a custom control in .NET - in WinForms,WebForms, Sharepoint and whatnot.

One of the designer attributes you can put on a control's properties is the System.ComponentModel.DefaultValue attribute, that defines the default value for a property if no specific value has been assigned to it. A common (and understandable) misconception is that setting this attribute will set the specified value for the property.

This is not the case.

The DefaultValue attribute relates to serialization of the value by the framework. Since the DefaultValue is assumed to be the same as the initial value set in code, the framework responsible for serializing and restoring the property's values (the Visual Studio IDE, the Web Parts Framework, etc) will skip serialization of the value if it matches the default value.

Setting the DefaultValue attribute will not actually set the value of the member, and we will get confusing and unexpected results at runtime if we assume it will.

Caveat Developer

3 Comments

Comments have been disabled for this content.