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 stringisnullbecause the value is of typebool, notstring. 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:
And you’re done.
this[UserMediaServerKey]will return theDefaultValuecorrectly typed if there is none in the configuration file. If you ever had to change the string conversion process, put aTypeConverterAttributeon the configuration property. But that isn’t necessary here.