Optional boolean defaults ConfigurationSection
I created a custom config 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; }
}
I understand that if the property is not defined in the config file then it is returned DefaultValue
.
However, in the above case, a is ArgumentNullException
thrown into bool.Parse(...)
, which means that the accessor is executed by default even if the config property is not defined.
Of course, I can change the accessor property 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 is the point of the property DefaultValue
?
source to share
this[UseMediaServerKey] as string
null
because the value is of type bool
, not string
. You don't need to do string conversions in the custom configuration section: everything is done for you using the framework.
Simplify your code:
public bool UseMediaServer
{
get { return (bool) this[UseMediaServerKey]; }
set { this[UseMediaServerKey] = value; }
}
And you're done. this[UserMediaServerKey]
will return DefaultValue
correctly entered if not in the config file. If you've ever had to change the string conversion process, put the property TypeConverterAttribute
in a config property. But this is not needed here.
source to share