Archive

Posts Tagged ‘Conditions’

Suggestion: If and while etc. clauses should accept bool? in C#

At TrackingCam app (http://TrackingCam.codeplex.com) I have the following WPF code, where cbTrackingPresenter is a CheckBox control defined in my MainWindow’s XAML:

private void cbTrackingPresenter_Checked(object sender, RoutedEventArgs e)
{
      if (cbTrackingPresenter.IsChecked == true)
          StartTrackingPresenter();
      else
          StopTrackingPresenter();
}

Note the (redundant in my opinion) == true pattern used there. If the == true is omitted, you get the compile-time error "CS0266", with message "Cannot implicitly convert type ‘bool?’ to ‘bool’. An explicit conversion exists (are you missing a cast?)"

Why not make the "if" clause (and "while" and any clause accepts a boolean/condition) more clever and have it accept bool? too? It would only fire the condition if the value is "true" (not if it is false or null) in that case.

You can vote for this suggestion at:

http://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/11038227-if-should-accept-bool

%d bloggers like this: