DefaultValue attribute is not working with my Auto Property
Solution 1
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
Solution 2
[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;
Related videos on Youtube
Ahmed Magdy
My name is Ahmed Magdy, I'm working as Senior Customer Engineer <developer /> at Microsoft with 16+ years experience in software development. LinkedIn - Stackoverflow Careers - @amgdy Founder of HackItRight - @hackitright
Updated on July 09, 2022Comments
-
Ahmed Magdy almost 2 years
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 abool
variable, does anyone have a clue what is wrong!?-
marbel82 over 7 years
-
-
Ahmed Magdy over 14 yearsThank you Philippe, so I think the only solution is from the constructor. thanks
-
Admin almost 11 yearsThis 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.
-
KOGRA almost 3 yearsHello 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. -
Marc Gravell almost 3 years@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)