Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Setting a default value for C# Auto-implemented properties

4.83/5 (14 votes)
7 Jan 2012CPOL 133.3K  
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:
C#
[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...
C#
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]

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)