Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom ConfigurationSection default boolean values

Tags:

c#

.net

I have created a custom configuration section with the following property:

private const string UseMediaServerKey = "useMediaServer";
[ConfigurationProperty(UseMediaServerKey, IsRequired = false, DefaultValue = false)]
public bool UseMediaServer
{
    get { return bool.Parse(this[UseMediaServerKey] as string); }
    set { this[UseMediaServerKey] = value; }
}

My understanding is that if the property is not defined in the configuration file then the DefaultValue should be returned.

However, in the above case a ArgumentNullException is thrown at bool.Parse(...) meaning the default accessor is executed even when the configuration property is not defined.

Of course I could change the property accessor to:

    private const string UseMediaServerKey = "useMediaServer";
    [ConfigurationProperty(UseMediaServerKey, IsRequired = false)]
    public bool UseMediaServer
    {
        get {
            bool result;
            if (bool.TryParse(this[UseMediaServerKey] as string, out result))
            {
                return result;
            }

            return false;
        }
        set { this[UseMediaServerKey] = value; }
    }

But then, what's the point of the DefaultValue property?

like image 249
Ben Foster Avatar asked Jul 27 '26 09:07

Ben Foster


1 Answers

this[UseMediaServerKey] as string is null because the value is of type bool, not string. You don't have to do any string conversion in a custom configuration section: everything is handled for you by the framework.

Simplify your code to:

public bool UseMediaServer
{
    get { return (bool) this[UseMediaServerKey]; }
    set { this[UseMediaServerKey] = value; }
}

And you're done. this[UserMediaServerKey] will return the DefaultValue correctly typed if there is none in the configuration file. If you ever had to change the string conversion process, put a TypeConverterAttribute on the configuration property. But that isn't necessary here.

like image 93
Julien Lebosquain Avatar answered Jul 30 '26 00:07

Julien Lebosquain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!