Setting a default value for C# Auto-implemented properties






4.83/5 (12 votes)
One of the things missing from C# is the ability to set a default value of auto-implemented properties. You can set a default for variable backed properties, and you can set them for the designer. This does it for you.
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."
No. I won't. I don't want the clutter.
But, they forgot they gave us Reflection...
If in your constructor, you read through the list of your class properties, you can get access to the default values...
public MyClass()
{
// Use the DefaultValue propety of each property to actually set it, via reflection.
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(this))
{
DefaultValueAttribute attr = (DefaultValueAttribute)prop.Attributes[typeof(DefaultValueAttribute)];
if (attr != null)
{
prop.SetValue(this, attr.Value);
}
}
}
You won't want to do this in controls: it would override any values you set in the designer!
[edit]Addendum regarding auto-indentation removed - OriginalGriff[/edit]