BLACKTOP: Writings From the Road

The Trouble with And

Here's something I've seen several times that can lead to bugs.  C# has two logical-and operators: & and &&.  If you come from a C++ background, it's entirely natural to use the && operator.  But there is a difference between the two operators: the && operator is a short-circuit operator.

  • The & operator always evaluates both the left and right side expressions
  • The && operator always evaluates the left side expression, but only evaluates the right side if the left side was true

This means with the && operator, both expressions might not be evaluated.  To get the most efficient use of the && operator, you should put the key expression that is most likely to be false on the left hand side.

Published Sunday, August 10, 2008 4:32 PM by DavidL
Filed under:

Comments

No Comments
Anonymous comments are disabled

About DavidL

I've been in IT over 15 years. Along the way, I've worked on mainframe applications (ugh) and UNIX (double ugh); I've done client server applications with VB and C++ and web applications with ASP. My favorite, though, is .NET. I've been working with .NET since beta 1 of 1.0 (I think they used punched cards back then) and I've always been pleased by the way it lets the developer focus on the business problem instead of housekeeping. For the last 7 years I have been a corporate developer in imaging and workflow with another company's product. After seeing what blackpearl can do, I am blown away by how quickly an application can come together. I'm looking forward to being part of something big!