.Net DefaultValueAttribute on Properties

I got this code in a user control:

[DefaultValue(typeof(Color), "Red")]
public Color MyColor { get; set; }

How can I change MyColor to be its default value?


The DefaultValueAttribute does not set the property to the value, it is purely informational. The Visual Studio designer will display this value as non-bold and other values as bold (changed), but you'll still have to set the property to the value in the constructor.

The designer will generate code for the property if the value was set by the user, but you can remove that code by right clicking on the property and clicking Reset.


DefaultValueAttribute is not used by the compiler, and (perhaps confusingly) it doesn't set the initial value. You need to do this your self in the constructor. Places that do use DefaultValueAttribute include:

  • PropertyDescriptor - provides ShouldSerializeValue (used by PropertyGrid etc)
  • XmlSerializer / DataContractSerializer / etc (serialization frameworks) - for deciding whether it needs to be included

Instead, add a constructor:

public MyType() {
  MyColor = Color.Red;
}

(if it is a struct with a custom constructor, you need to call :base() first)