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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With