24

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

1

3 Answers 3

43

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

1
  • 2
    Thank you Philippe, so I think the only solution is from the constructor. thanks Dec 31, 2009 at 6:39
18

[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;
2
  • Hello its old question. But is it safe for code generation that use only auto-implemented property now? and remove the retreiveAllInfo field? I mean public bool RetreiveAllInfo {get;set;} = true directly? Why I still see most UI libraries use old fashion.
    – KOGRA
    May 31, 2021 at 21:19
  • 1
    @KOGRA "yes, that's fine", and "because like this answer: they were written when that syntax didn't exist" (this is the "auto property initializer" feature in C# 6) Jun 1, 2021 at 7:14
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);
        }
   }
1
  • 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.
    – user743382
    Jun 21, 2013 at 10:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.