23

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!?

Ahmed Magdy
  • 5,256
  • 8
  • 36
  • 74
  • 1
    [Similar question](http://stackoverflow.com/questions/705553/net-defaultvalueattribute-on-properties). In VS2015: `public bool RetrieveAllInfo { get; set; } = true;` It's [C# 6](https://blogs.msdn.microsoft.com/csharpfaq/2014/11/20/new-features-in-c-6/) feature. – marbel82 Nov 08 '16 at 13:17

3 Answers3

38

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

Philippe Leybaert
  • 155,903
  • 29
  • 200
  • 218
16

[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; }
}
Marc Gravell
  • 927,783
  • 236
  • 2,422
  • 2,784
0

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);
        }
   }
  • 5
    This is dangerous and shouldn't be used. This sets the properties of derived classes before the base class constructor has finished, before the derived class has had a chance to set up anything needed to make the property setters work. –  Jun 21 '13 at 10:41