Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying a Nullable bool in C#

I've come across a curious problem with the following code. It compiles fine although 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 better to get around this problem?

Edit 07/02/2012 16:52

Properties.Settings.Default.autorefresh

The above is a bool, not a string.

like image 571
wonea Avatar asked Dec 22 '22 02:12

wonea


1 Answers

I think what you want is:

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

In light of your comments, it appears you were unneccessarily assigning the value of autorefresh to a Nullable<bool>. In terms of safeguarding the data, the Settings will return you the default value for that type if it is invalid or missing (which would be false for boolean's). Therefore, your code should simply be:

Enabled = Properties.Settings.Default.autorefresh;
like image 66
James Avatar answered Dec 24 '22 01:12

James