Short-circuit Boolean evaluation in C# ?
Does C# allow short-circuit evaluation of Boolean expressions? That is, if you have an expression such as
if (test1) & (test2) {....}
when test1 is false, there is no reason to evaluate test2 and a language which supports short-circuit evaluation never looks at the second test because the result will obviously be false. From what I can tell, C# doesn't do that, at least by default. Is there a compiler directive or attribute which will allow that?
fishsqzr
Junior Poster in Training
57 posts since Aug 2007
Reputation Points: 10
Solved Threads: 1
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
In that case, C# has a bug. I have a class with a string named FieldName. Until the string has a value assigned, it is null. I want to test for null, but I also want to see if the string has been assigned an empty string (a string with length zero) since there are situations where the user may erase its contents. So, I use the following
if ((cr.FieldName == null) | (cr.FieldName.Length == 0))
throw new Exception("Null FieldName in SQLNumStrategy");
If short-circuit is working right, it should never check the FieldName.Length property if FieldName is null becuase the result of the statement is already known. However, it does try to check, which raises a different exception (with the wrong message). I find I must break up the test into two separate if statements, testing for null first. Then, if FieldName is null, the correct exception is thrown and Length is never checked.
Other kinds short-circuit evaluations seem to work, so the bug appears related to the test for null. I guess this is just yet another C# 'feature'.
fishsqzr
Junior Poster in Training
57 posts since Aug 2007
Reputation Points: 10
Solved Threads: 1
Thanks. That was a stupid mistake on my part, and I didn't know about IsNullOrEmpty at all.
fishsqzr
Junior Poster in Training
57 posts since Aug 2007
Reputation Points: 10
Solved Threads: 1
I merely answered the question posed.
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439