Request in Nullable bool in C #

I ran into a curious problem with the following code. It compiles fine, but Resharper highlights the code segment (autorefresh == null) , notifying me. Expression is always false

 bool? autorefresh = Properties.Settings.Default.autorefresh; autorefresh = (autorefresh == null) ? false : autorefresh; Enabled = (bool)autorefresh; 

Any ideas how best to get around this problem?

Edit 07/02/2012 16:52

 Properties.Settings.Default.autorefresh 

The above value is bool , not string .

+4
source share
7 answers

I think you want:

 Enabled = Properties.Settings.Default.autorefresh ?? false; 

In the light of your comments, it seems that you have not assigned an autorefresh value to Nullable<bool> . Regarding data protection, Settings will return you the default value for this type if it is invalid or missing (which would be false for boolean ). Therefore, your code should be simple:

 Enabled = Properties.Settings.Default.autorefresh; 
+6
source

Think about it:

 bool? autorefresh = Properties.Settings.Default.autorefresh; // ^^^ this is a non-nullable Boolean 

Properties.Settings.Default.autorefresh not null, so it will be either true or false.

Therefore, a zero local autorefresh will also be either true or false, since it is initialized to a value that is either true or false.

 autorefresh = (autorefresh == null) ? false : autorefresh; // ^^^^ therefore this test will never succeed 

Therefore, this is equivalent to:

 autorefresh = autorefresh; 

which is obviously pointless. (And, as others have pointed out, autorefresh ?? false is the best way to write this code anyway.)

Question: why do you have a local variable in the first place? Why not just say:

 Enabled = Properties.Settings.Default.autorefresh; 

?

+3
source
  bool? autorefresh = Properties.Settings.Default.autorefresh ?? false; 

It is safe to make the following comparisons with operators with a zero value

 autorefresh == null 

or you can also compare

 autorefresh == true 

or

 autorefresh == false 
+1
source

You can also do this:

  Enabled = Properties.Settings.Default.autorefresh.GetValueOrDefault(false); 

There is no need to check for zeros if a null value can do this for you.

+1
source

Nullables has some interesting behavior. I would have to dig a bit to find out the exact reasons for what you see. Regardless, the correct way to check for NULL is to use the .HasValue method.

0
source

You can try the following:

 bool? autorefresh = Properties.Settings.Default.autorefresh; Enabled = (!autorefresh.HasValue) ? false : autorefresh.Value; 
0
source

The value of autorefresh is NULL, which means that autorefresh.Value can be null. I think you can do it

enable =! autorefresh.HasValue? false: autorefresh.Value;

0
source

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


All Articles