This is a mirror of official site: http://jasper-net.blogspot.com/

Setting a default value for C# Auto-implemented properties

| Sunday, January 22, 2012
If you auto-implement a property, it would be handy to be able to set a default value. Indeed, there is the System.ComponentModel.DefaultValueAttribute which you can set, perfectly happily:

[DefaultValue("-New Object-")]
public string MyString { get; set; }
[DefaultValue(240)]
public int MyInt { get; set; }
[DefaultValue(110)]
public int EnvelopeHeight { get; set; }
[DefaultValue(true)]
public bool MyBool { get; set; }

This compiles perfectly, and off you go.
The only problem is, this only affects the designer - not the runtime properties.
MSDN even makes this clear: DefaultValueAttribute Class[^]
 
"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."
 
Which means in layman's terms: "This is for the VS designer only - go away and use a backing variable."

Read more: Codeproject
QR: Setting-a-default-value-for-Csharp-Auto-implemente

Posted via email from Jasper-net

0 comments: