I have a custom configuration section in my web.config.
One of my classes is grabbing from this:
<myConfigSection LabelVisible="" TitleVisible="true"/>
I have things working for parsing if I have true or false, however if the attribute is blank I am getting errors. When the config section tries to map the class to the configuration section I get an error of "not a valid value for bool" on the 'LabelVisible' part.
How can I parse "" as false in my myConfigSection class?
I have tried this:
[ConfigurationProperty("labelsVisible", DefaultValue = true, IsRequired = false)]
public bool? LabelsVisible
{
get
{
return (bool?)this["labelsVisible"];
}
But when I try and use what is returned like so:
graph.Label.Visible = myConfigSection.LabelsVisible;
I get an error of:
'Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)
Your problem is that graph.Label.Visible
is of type bool
but myConfigSection.LabelsVisible
is of type bool?
. There is no implicit conversion from bool?
to bool
because this a narrowing conversion. There are several ways to solve this:
1: Cast myConfigSection.LabelsVisible
to a bool
:
graph.Label.Visible = (bool)myConfigSection.LabelsVisible;
2: Extract the underlying bool
value from myConfigSection.LabelsVisible
:
graph.Label.Visible = myConfigSection.LabelsVisible.Value;
3: Add logic to capture when myConfigSection.LabelsVisible
represents the null
value:
graph.Label.Visible = myConfigSection.LabelsVisible.HasValue ?
myConfigSection.LabelsVisible.Value : true;
4: Interalize this logic to myConfigSection.LabelsVisible
:
[ConfigurationProperty("labelsVisible", DefaultValue = true, IsRequired = false)]
public bool LabelsVisible {
get {
bool? b= (bool?)this["labelsVisible"];
return b.HasValue ? b.Value : true;
}
}
It is one of the latter two approaches that is best to avoid some exceptions that would occur if you use the other solutions when myConfigSection.LabelsVisible
represents the null
value. And the best solution is to internalize this logic into the myConfigSection.LabelsVisible
property getter.
This is a little dangerous, but technically works: (you'll get an InvalidOperationException if the value of the nullable is indeed null):
graph.Label.Visible = (bool)myConfigSection.LabelsVisible;
You should verify the nullable to see if it's been set:
bool defaultValue = true;
graph.Label.Visible = myConfigSection.LabelsVisible ?? defaultValue;
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