Russell Bearden
Russell Bearden

Reputation: 178

Is there any way in C# to automatically set the DefaultValueAttribute for properties that have default values set?

Is there anyway to implicitly carry out the following pattern?

    [DefaultValue(true)]
    public bool SomeBooleanProperty { get; set; } = true;

Repeating the default value in two locations just seems to be begging for mistakes somewhere and in any case seems very redundant. I can imagine some cases where having the DefaultValueAttribute automatically set to the default value (or any value) would be undesirable, but I think those would be the exception rather than the rule. And in those cases the solution would simply be to set the default value in the constructor rather than at declaration which I think is less burdensome than redundant code.

Upvotes: 2

Views: 418

Answers (1)

Gareth
Gareth

Reputation: 911

MSDN says this about the DefaultValueAttribute

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.

This article suggests doing something like this to avoid repeated code

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);
    }
}

Upvotes: 5

Related Questions