Archive

Posts Tagged ‘TrackingCam’

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

HowTo: show inner exception message if available, else outer one

Sometimes when you catch an exception in .NET, the message it prints out isn’t very informative, since it is wrapping another exception that had been thrown a bit inner in the code. That exception is in that case accessible via InnerException of the Exception instance.

That inner exception is also an Exception, so one would like to use its Message instead of the outer exception’s one, if an inner exception exists and, only if an inner exception doesn’t exist use the caught exception’s message. Here’s a clean-looking pattern I’ve coined up to achieve this while working on the TrackingCam application:

try

{

  //…

}

catch (Exception e)

{

  MessageBox.Show((e.InnerException ?? e).Message);

}

the ?? operator returns e.InnerException if it is not null, else falls back to returning e. Those two results are both of type Exception, so you can use Message on them, by putting the ?? operator’s expression in parentheses.

%d bloggers like this: