DefaultValue Attribute as Initial Value

Visual Studio Properties

C# lets the programming define a default value on a class property, so that GUI widgets can test the property to see if it still has the default value. Visual Studio, for example, bolds any properties that have a non-default value, making them easy to pick out.

Unfortunately, the default value isn't used to actually initialize the property. The initialization must be done elsewhere in the code, typically in the class's constructor. Having to type the same value in two separate places in the code is error-prone, since it's easy to inadvertently change the value in one place and forget to change it in the other.

public class Widget
{
    [DefaultValue(5)]
    public int WidgetLength { get; set; }

    public Widget()
    {
         WidgetLength = 5;
    }
}

With only one property in the class, the chances of an error are small. However, when you have dozens of properties and the constructor is hundreds of lines away from the DefaultValue, mismatches are bound to happen. Furthermore, so many people assume that setting the DefaultValue will initialize the property that Microsoft issued a Knowledge Base bulletin to clarify the matter. (Why can't they just make the documentation more explicit?)

Since I hate maintaining error-prone code, I wrote a function that initializes all of an instance's properties using the DefaultValue attributes. I can set the DefaultValue attribute on each property, call the function once in the constructor, and forget about it.

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);
     }
}
  • Share/Bookmark

1 comment to DefaultValue Attribute as Initial Value

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>