2009-07-30

Difference between logical operators in C#

Yes, you’ve probably seen that the AND and OR logical operators have two ways of being written in C#: The first way is like this: && (AND), || (OR), and the second is this: & (AND), | (OR). In case you didn’t notice the difference, the first ones use a double operator, while the last ones use only one.

As you already might know, AND operator returns true if both sides of an expression are true, and OR operator returns true if at least one side of the expression is true.

Even though most of us programmers actually know that there are two “ways” to write the AND and OR operators, few know (that was my case before I looked it up) the difference between both. Well, here it is:

When you use double logical operators (which is probably most of the time), the compiler only evaluates the right part of the expression if the first one doesn’t already make the expression false. The opposite happens when you use single logical operators: both sides of the expression get evaluated no matter what. Let’s clear that out with an example:

  1: if(myDataSet.Tables.Count > 0 && myDataSet.Tables[0].Rows.Count > 0)
  2: {
  3:    //Do something
  4: }

Because we’re using the double AND operator (&&), the compiler will automatically mark the whole expression as false if it finds that the left side of it is already false, without even bothering to evaluate the right side. This is very useful in this specific case with the DataSet, because sometimes we need to evaluate both that the DataSet has a table, and that table has at least one row. That will save us having to use two nested if statements:

  1: if(myDataSet.Tables.Count > 0)
  2: {
  3:    if(myDataSet.Tables[0].Rows.Count > 0)
  4:    {
  5:       //Do something
  6:    }
  7: }

Now, if we use only the single AND operator, the compiler will evaluate both sides of the expression no matter what, so this code:

  1: if(myDataSet.Tables.Count > 0 & myDataSet.Tables[0].Rows.Count > 0)
  2: {
  3:    //Do something
  4: }

will result in an ArgumentNullException if our DataSet doesn’t have a table, caused by the myDataSet.Tables[0].Rows.Count > 0 comparison.

There’s one more logical operator, the XOR (^), which will return true only if both sides of the expression are different (one is true and the other is false). This, in practical terms, is the same as the DIFFERENT (!=) operator, and it doesn’t have a “double” counterpart, because obviously in this case, both sides of the expression have to always be evaluated.

No hay comentarios:

Publicar un comentario

Your tips and thoughts are always welcome, and they provide good motivation: