C#.NET: Difference between | and || (bitwise vs conditional OR)
We have a new coder at work who is in love with the Boolean inclusive OR operator (pipe symbol | or as I have called it until now, bitwise OR), and he uses it for conditional expressions. I knew there had to be a difference between | and the conditional OR operator ||, but I wasn’t sure what it was. The code seemed to work fine, but it was nagging me.
So I finally got around to looking it up.
A behavior that I take for granted in C# is the result of using the conditional operators (two pipe symbols || or 2 ampersand symbols && ) with boolean expressions. For an OR, the first expression that evaluates to true stops the evaluations. For AND, the first one that evaluates to false stops them.
This makes a big difference when doing checking for nulls or other conditions that would cause runtime exceptions without having to nest the checks.
This code runs fine, even with no dataset.
DataSet ds = null; // code here to load dataset, etc if (ds != null && ds.Tables != null && ds.Tables[0] != null && ds.Tables.Count > 0) { //do something with the table }
This code throws a runtime exception, because ds is null, so you get a NullReferenceException when it proceeds to go on and hit ds.Tables.
DataSet ds = null; // code here to load dataset, etc if (ds != null & ds.Tables != null & ds.Tables[0] != null & ds.Tables.Count > 0) { //do something with the table }
As an aside, I believe the default for VB.NET OR and AND is to evaluate all sides all the time as Boolean Inclusive, since I’ve been flummoxed by null reference exceptions I didn’t expect when trying similar coding. One of these days I’ll look that up, too. =)
Got more tips or goodies for us? Please share them in the comments!

