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?

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?

So basically you think c# doesn't support short-circuit evaluation ?
Have a look here: http://msdn2.microsoft.com/en-us/library/2a723cdk(VS.71).aspx

@iamthwee: Those kind of answers are not very helpful, altough they might amuse you (weird sense of humour). In case you intend to post such a crap again in the future, why don't you think twice about it and (possibly) keep out of the discussion?

Is that not what a SELECT / SWITCH / CASE statement is for? It essentially does the same thing.

Btw that was a stupid answer iamthwee :P

Jenni

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'.

The short-circuit is working right, however your code is not, a short-circuit evaluation should be written like this :

if ((cr.FieldName == null) || (cr.FieldName.Length == 0))
                throw new Exception("Null FieldName in SQLNumStrategy");

Note the 2 pipes (which represent a conditional-OR)
The framework proposes also a convenience method for your particular case which is string.IsNullOrEmpty():
http://msdn2.microsoft.com/en-us/library/system.string.isnullorempty.aspx

Thanks. That was a stupid mistake on my part, and I didn't know about IsNullOrEmpty at all.

This question has already been answered. Start a new discussion instead.