Parsing logic from a configuration section in web.config

I have a custom configuration section in my web.config.

One of my classes seized on this:

<myConfigSection LabelVisible="" TitleVisible="true"/>

I have things working for parsing, if I have true or false, however, if the attribute is empty, I get errors. When the configuration section tries to map the class to the configuration section, I get the error "invalid value for bool" in the "LabelVisible" part.

How can I parse "" as false in my myConfigSection class?

I tried this:

    [ConfigurationProperty("labelsVisible", DefaultValue = true, IsRequired = false)]
    public bool? LabelsVisible
    {
        get
        {

            return (bool?)this["labelsVisible"];

        }

But when I try to use something that returns like this:

graph.Label.Visible = myConfigSection.LabelsVisible;

I get an error message:

'Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)  
+3
source share
4 answers

, graph.Label.Visible bool, myConfigSection.LabelsVisible bool?. bool? bool, . :

1: myConfigSection.LabelsVisible bool:

graph.Label.Visible = (bool)myConfigSection.LabelsVisible;

2: bool myConfigSection.LabelsVisible:

graph.Label.Visible = myConfigSection.LabelsVisible.Value;

3: , myConfigSection.LabelsVisible null:

graph.Label.Visible = myConfigSection.LabelsVisible.HasValue ?
                          myConfigSection.LabelsVisible.Value : true;

4: myConfigSection.LabelsVisible:

[ConfigurationProperty("labelsVisible", DefaultValue = true, IsRequired = false)]
public bool LabelsVisible {
    get {
        bool? b= (bool?)this["labelsVisible"];
        return b.HasValue ? b.Value : true;
    }
}

, , , , myConfigSection.LabelsVisible null. , getter myConfigSection.LabelsVisible.

+8

, : ( InvalidOperationException, nullable null):

graph.Label.Visible = (bool)myConfigSection.LabelsVisible;

nullable, , :

bool defaultValue = true;
graph.Label.Visible = myConfigSection.LabelsVisible ?? defaultValue;
+3

to try:

graph.Label.Visible = myConfigSection.LabelsVisible.HasValue ? myConfigSection.LabelsVisible.Value : false;
+2
source
if (myConfigSection.LabelsVisible.HasValue)
{
    graph.Label.Visible = myConfigSection.LabelsVisible.Value;
}
0
source

Source: https://habr.com/ru/post/1721906/


All Articles