I am displaying information as a checkbox with ThreeState
enabled, and want to use a nullable boolean in simplest way possible.
Currently I am using a nested ternary expression; but is there a clearer way?
bool? foo = null;
checkBox1.CheckState = foo.HasValue ?
(foo == true ? CheckState.Checked : CheckState.Unchecked) :
CheckState.Indeterminate;
* Note that the checkbox and form is read-only.
That's how I would do it.
I would add an extension method to clean it up a bit.
public static CheckState ToCheckboxState(this bool booleanValue)
{
return booleanValue.ToCheckboxState();
}
public static CheckState ToCheckboxState(this bool? booleanValue)
{
return booleanValue.HasValue ?
(booleanValue == true ? CheckState.Checked : CheckState.Unchecked) :
CheckState.Indeterminate;
}
More clear is an arguable statement. For example I could say that this is more clear.
if(foo.HasValue)
{
if(foo == true)
checkBox1.CheckState = CheckState.Checked;
else
checkBox1.CheckState = CheckState.Unchecked;
}
else
checkBox1.CheckState = CheckState.Indeterminate;
Another option would be to create a method just for this:
checkBox1.CheckState = GetCheckState(foo);
public CheckState GetCheckState(bool? foo)
{
if(foo.HasValue)
{
if(foo == true)
return CheckState.Checked;
else
return CheckState.Unchecked;
}
else
return CheckState.Indeterminate
}
However I like your code.
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