.NET DefaultValue attribute

I've heard people say a few different things about the DefaultValue attribute including:

  • "It sets the value of the property before anything else uses it."
  • "It doesn't work for autoproperties."
  • "It's only for decoration. You must manually set actual default values."

Which (if any) is right? Does DefaultValue actually set default values? Are there cases where it doesn't work? Is it best just not to use it?


The place where I typically used DefaultValue is for classes which are serialized/deserialized to XML. It does not set the default value during instantiation and doesn't impact autoproperties.

From MSDN:

A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.

MSDN - DefaultValueAttribute Class


Edit: As Roland points out, and as others mentioned in their answers the attribute is also used by the Form Designer


To update this four years later: Currently, setting JSON.net's DefaultValueHandling parameter makes DefaultValue work the way @aaron expected:

[JsonProperty("allowUploading",DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
[DefaultValue(true)]
public bool AllowUploading { get; set; }

Like all attributes, it's meta data, and as such "It's only for decoration. You must manually set actual default values." is closest.

MSDN goes on to say about DefaultValueAttribute:

A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.

i.e. You still need to make the constructor match what you say is the default value so that code that trusts it still works, such as the built in XML Serialization will use them to work out whether to serialise the property or not; similarly the form designer will use the DefaultValues to work out what code needs to be automatically generated.