Why does ConfigurationValidator validate the default value of a ConfigurationProperty even if IsRequired is true?

Viewed 3973

Let's say I have a configuration property that looks like this. Note that there is no default value.

[ConfigurationProperty("x", IsRequired = true)]
[StringValidator(MinLength = 1)]
public string X
{
    get { return (string)this["x"]; }
    set { this["x"] = value; }
}

Now I add my section like this:

<mySection x="123" />

I'll get this error:

The value for the property 'x' is not valid. The error is: The string must be at least 1 characters long.

It works if I change the configuration property to include a default like this:

[ConfigurationProperty("x", DefaultValue="abc", IsRequired = true)]
[StringValidator(MinLength = 1)]
public string X
{
    get { return (string)this["x"]; }
    set { this["x"] = value; }
}

This implies that validator validates the default value even if IsRequired is true. It also means that I have to include a dummy default values on all my properties to pass validation even though they won't actually be used.

Is this just bad design or is there a valid reason for this behavior?

4 Answers

As said previously, this does not help in getting a validation without having to specify a default value for a property, which then makes the IsRequired property of the ConfigurationPropertyAttribute useless.

Related