69

Assume myObj is null. Is it safe to write this?

if(myObj != null && myObj.SomeString != null)

I know some languages won't execute the second expression because the && evaluates to false before the second part is executed.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
patrick
  • 16,091
  • 29
  • 100
  • 164

9 Answers9

99

Yes. In C# && and || are short-circuiting and thus evaluates the right side only if the left side doesn't already determine the result. The operators & and | on the other hand don't short-circuit and always evaluate both sides.

The spec says:

The && and || operators are called the conditional logical operators. They are also called the “shortcircuiting” logical operators.
...
The operation x && y corresponds to the operation x & y, except that y is evaluated only if x is true
...
The operation x && y is evaluated as (bool)x ? (bool)y : false. In other words, x is first evaluated and converted to type bool. Then, if x is true, y is evaluated and converted to type bool, and this becomes the result of the operation. Otherwise, the result of the operation is false.

(C# Language Specification Version 4.0 - 7.12 Conditional logical operators)

One interesting property of && and || is that they are short circuiting even if they don't operate on bools, but types where the user overloaded the operators & or | together with the true and false operator.

The operation x && y is evaluated as T.false((T)x) ? (T)x : T.&((T)x, y), where T.false((T)x) is an invocation of the operator false declared in T, and T.&((T)x, y) is an invocation of the selected operator &. In addition, the value (T)x shall only be evaluated once.

In other words, x is first evaluated and converted to type T and operator false is invoked on the result to determine if x is definitely false.
Then, if x is definitely false, the result of the operation is the value previously computed for x converted to type T.
Otherwise, y is evaluated, and the selected operator & is invoked on the value previously computed for x converted to type T and the value computed for y to produce the result of the operation.

(C# Language Specification Version 4.0 - 7.12.2 User-defined conditional logical operators)

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • 7
    That last paragraph was a little *too* interesting...made my head hurt. :) – Joe Enos Jan 27 '11 at 19:20
  • 1
    It looks complicated, but it's not that hard. It simply doesn't evaluate the right side if the `false` operator on the left side returns `true` and returns the left side instead, and else invokes the custom `&` operator. So it mimics the short circuiting behavior `bool`s have. The typical application of this is an extended `bool` that can have a third state. For example you could implement something similar to `DBBol` or `bool?` with that. – CodesInChaos Jan 27 '11 at 19:25
  • 1
    I wish we had `&&=` and `||=` operators. – Nikola Malešević Sep 24 '21 at 08:49
17

Yes, C# uses logical short-circuiting.

Note that although C# (and some other .NET languages) behave this way, it is a property of the language, not the CLR.

harpo
  • 41,820
  • 13
  • 96
  • 131
  • 13
    Actually, VB.NET behaves this way when using `AndAlso` and `OrElse`, *not* on `And` and `Or`, which is likely what 90% of people always use. – Adam Robinson Jan 27 '11 at 19:03
  • 1
    It is also important to note that this not only an implementation detail (which can change at any time) but part of the C# Specification (which will not change in this respect). – Olivier Jacot-Descombes Dec 06 '17 at 15:18
6

I know I'm late to the party, but in C# 6.0 you can do this too:

if(myObj?.SomeString != null)

Which is the same thing as above.

Also see: What does question mark and dot operator ?. mean in C# 6.0?

Community
  • 1
  • 1
Drew Delano
  • 1,421
  • 16
  • 21
  • Answer does not answer the question and is a suggestion on syntactic sugar that should be a comment. – Billy Bob Mar 25 '21 at 18:53
  • 1
    @BillyBob The answer to OPs original question is yes, and that has been well established by all of the other answers on here. This goes more toward answering "does the example code provided even need short circuiting" – Drew Delano Mar 26 '21 at 21:23
4

Your code is safe - && and || are both short-circuited. You can use non-short-circuited operators & or |, which evaluate both ends, but I really don't see that in much production code.

Joe Enos
  • 39,478
  • 11
  • 80
  • 136
3

sure, it's safe on C#, if the first operand is false then the second is never evaluated.

Mauricio
  • 5,854
  • 2
  • 28
  • 34
1

In C#, && and || are short-circuited, meaning that the first condition is evaluated and the rest is ignored if the answer is determined.

In VB.NET, AndAlso and OrElse are also short-circuited.

In javaScript, && and || are short-circuited too.

I mention VB.NET to show that the ugly red-headed step-child of .net also has cool stuff too, sometimes.

I mention javaScript, because if you are doing web development then you probably might also use javaScript.

John Grabauskas
  • 310
  • 2
  • 5
  • Essentially, `a || b` is equivalent to `a ? a : b`, and `a && b` is equivalent to `a ? b : a`, except that a is evaluated only once. This is more noticeable in JavaScript, where operands of arbitrary type can be used. Other languages such as C don't follow this principle - they accept operands of non-boolean types but always return a boolean value. – Stewart Feb 11 '20 at 15:58
1

It is perfectly safe. C# is one of those languages.

Ilya Kogan
  • 21,995
  • 15
  • 85
  • 141
0

Yes, C# and most languages compute the if sentences from left to right.

VB6 by the way will compute the whole thing, and throw an exception if it's null...

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
  • This is... not exactly wrong, but misleading on so many levels. (1) Curly braces languages is just a small subset of the languages that do this. (2) Reversing the input before parsing it is madness, so about no language does this. (3) Regardless of how it's parsed, short-curcuiting is runtime semantics. (4) See comment to harpo's answer regarding VB - `And` doesn't short-curcuit, but `&` doesn't either. (Perhaps 2+3 are because you confuse parsing with something that happens at runtime...) –  Jan 27 '11 at 19:09
0

an example is

if(strString != null && strString.Length > 0)

This line would cause a null exception if both sides executed.

Interesting side note. The above example is quite a bit faster than the IsNullorEmpty method.

Bengie
  • 1,035
  • 5
  • 10