23
votes

I have the following Auto Property

[DefaultValue(true)]
public bool RetrieveAllInfo { get; set; }

when I try to use it inside the code i find the default false for is false I assume this is the default value to a bool variable, does anyone have a clue what is wrong!?

3
Similar question. In VS2015: public bool RetrieveAllInfo { get; set; } = true; It's C# 6 feature.marbel82

3 Answers

38
votes

The DefaultValue attribute is only used to tell the Visual Studio Designers (for example when designing a form) what the default value of a property is. It doesn't set the actual default value of the attribute in code.

More info here: http://support.microsoft.com/kb/311339

17
votes

[DefaultValue] is only used by (for example) serialization APIs (like XmlSerializer), and some UI elements (like PropertyGrid). It doesn't set the value itself; you must use a constructor for that:

public MyType()
{
    RetrieveAllInfo = true;
}

or set the field manually, i.e. not using an automatically implemented-property:

private bool retrieveAllInfo = true;
[DefaultValue(true)]
public bool RetrieveAllInfo {
    get {return retrieveAllInfo; }
    set {retrieveAllInfo = value; }
}

Or, with more recent C# versions (C# 6 or above):

[DefaultValue(true)]
public bool RetrieveAllInfo { get; set; } = true;
0
votes

One hack for this is on this link.

In short, call this function at the end of constructor.

static public void ApplyDefaultValues(object self)
   {
        foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(self)) {
            DefaultValueAttribute attr = prop.Attributes[typeof(DefaultValueAttribute)] as DefaultValueAttribute;
            if (attr == null) continue;
            prop.SetValue(self, attr.Value);
        }
   }