Is relying on && short-circuiting safe in .NET? - c#

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.

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)

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.

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?

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.

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

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

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.

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

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.

Related

How does Bitwise AND interact with boolean values?

I have come across a piece of code that I can't wrap my head around:
public void Connect()
{
if (!(!string.IsNullOrEmpty(_vpnConnectionName) & !string.IsNullOrEmpty(_ipToPing)))
{
return;
}
GetConnected();
}
I've researched the single ampersand on SO and elsewhere, and found it is a Bitwise AND operand. However the explanations all revolve around integers.
I can understand the applicability of bitwise operations on integers, but how are they applicable to booleans?
It is a logical operator on bools that evaluates both sides regardless of the value of the left side.
For bool, & isn't a bitwise AND operator - it's the non-short-circuiting logical AND operator - it always evaluates both arguments - as opposed to the "usual" && operator that only evaluates its second argument if its first argument is true.
(Realised that it may not be obvious, that the first & above is linked to the actual documentation)

Checking hierarchy of null in if statement

In a complex object like OperationContext is it safe to write such code:
if(OperationContext.Current!=null &&
OperationContext.Current.ServiceSecurityContext !=null &&
OperationContext.Current.ServiceSecurityContext.WindowsIdentity !=null)
Or do I need to separate the code to three if statements?
My question is if the OperationContext.Current is null I afraid that OperationContext.Current.ServiceSecurityContext will throw a NullReferenceException.
The && operator in C# uses short circuit evalulation so your code is fine.
What this means is the left-hand side of the condition is evaluated first and if it passes the right-hand side is then evaluated.
It is safe. Right side of && is evaluated only if left side is true.
Here is the MSDN explanation:
The operation
x && y
corresponds to the operation
x & y
except that if x is false, y is not evaluated, because the result of
the AND operation is false no matter what the value of y is. This is
known as "short-circuit" evaluation.
It won't, please take a look at the definition of the && operator: http://msdn.microsoft.com/en-us/library/2a723cdk.aspx. If the first part is false, the second one is simply not evaluated.
Your code would throw that exception if you used the & operator.

Nullable Types and Operators

I was reading about Nullable Types and Operators from Wrox and came across the following statement:
When comparing nullable types, if only one of the operands is null, the comparison will always equate to false. This means that you cannot assume a condition is true just because its opposite is false.
Now, I get what the first statement means but didn't get the second statement.
Could you please elaborate?
It appears like the quote is saying that any comparison at all with a null type will return null, regardless of the operand.
So something like (null != 5) Would return false, where (null == 5) would also return false.
Now, the funny thing is, that when I ran a program, null != 5 returned true, so while I can't verify that statement for c# 2.0, it's definitely not true anymore in c# 4.0 +
This is the sample code I've used:
int? a = null;
int? b = 5;
if (a != b)
{
Console.WriteLine("A != B");
}
if (a == b)
{
Console.WriteLine("A == B");
}
This is the output
A != B
Press any key to continue . . .
That quote is wrong, MSDN is the official source: http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx
When you perform comparisons with nullable types, if the value of one
of the nullable types is null and the other is not, all comparisons
evaluate to false except for != (not equal).
The second statement simply means that a comparison and its opposite may be both false, eg a>=b and a<b are both false.
Here's the logic. Null kind of means an unknown value. Now try to calculate 5<null, 5<=null, 5==null, 5>=null, 5>null. You can't exactly calculate any of these, they are not true or false either, they are unknown, but false makes a bit more sense than true. The exception is 5!=null. An exact number is not unknown, so it makes a bit more sense that it's true than false. So == and != are the opposite of each other, it's the easy case, but you can't say that for greater-less comparisons. It was a design choice when they made C#/.NET.
SQL on the other hand got it quite right I think with 3-valued-logic, see here: http://en.wikipedia.org/wiki/Null_%28SQL%29#Comparisons_with_NULL_and_the_three-valued_logic_.283VL.29

Multiple Conditions in If Statement or Splitting

when i am using if statements with multiple conditions, how are they managed in the compiler?
A) Will it ignore the second Statement, if the first statement is not fulfilled or vice versa?
If(time > 3.0 && hitEnabled)
B) Late Defintions are often recommended, so should i prefere to use one condition in if statements?
if(time > 3.0)
if(hitEnabled)
Thanks!
if(time > 3.0 && hitEnabled)
In above statement hitEnabled will not be evaluated when time > 3.0 is false.
This is called short-circuit.
Following statement will evaluate hitEnabled even when time > 3.0 is false but returns true when both operands are true.
if(time > 3.0 & hitEnabled)//note bitwise &
if(time > 3.0)
if(hitEnabled)
Nested if statements are helpful when you need first condition to be checked many times etc.
if(time > 3.0 && hitEnabled)
{
//DoSomething1
}
if(time > 3.0 && flag)
{
//DoSomething2
}
This can be re written with nested if statements as follows
if(time > 3.0)
{
if(hitEnabled)
{
//DoSomething1
}
if(flag)
{
//DoSomething2
}
}
In this case I prefer nested if statement to avoid unnecessary checks
In case of an && if the first condition is false, the second condition will never be evaluated and the overall result is false. In case of an ||, if the first condition is true the second condition is not evaluated and the overall result is true. As Rob pointed out, it is known as short circuit evaluation.
This is useful in cases when we want to evaluate the second operand of the if statement only if the first operand returns true. For example, we may want to check for the validity of a variable before using it.
if(ptr != NULL && *ptr > x)
In this case the value of ptr will be checked against x only if it is not NULL.
A) It won't check hitEnabled if first condition will be false, if you want to do it you must use short-circuit AND (&) like below. Even if first condition will be False, it will check second one.
If(time > 3.0 & hitEnabled)
B) It strongly depends on what you want from you application and less on performance of your hardware. If you want to check both conditions in any case, B option is perfectly fine, but if you certain if you time > 3.0 is false and you don't want check second one, A option is preferable in my opinion. As I said before it is strongly depends on the logic of your program, so you can't get the right answer based on one line of code.
If you ask just about what better manner of writing without logic background, it's up to you. Both variants easy to read, if you follow code conventions.
The evaluation of the expression stops as soon as it is conclusively true or false.
This allows expressions like if (x != null && x.property ... as x.property will not be evaluated if x is null etc.
String someString = null;
if (someString != null && someString[4].Equals('a'))
{
//// not called
}
if (someString != null || someString[4].Equals('a'))
{
//// exception
}
Console.ReadLine();
In the first case:
If(time > 3.0 && hitEnabled)
If time > 3.0 is false then hitEnabled will never be checked. And it always starts checking conditions from left to right.
If you want to make sure that all conditions will be checked you should use || (logical OR) instead of && (logical AND) for example:
If(time > 3.0 || hitEnabled)
This:
if(time > 3.0 && hitEnabled)
equals
if(time > 3.0)
if(hitEnabled)
If the first condition is violated it wont check for the second one and it simply ignores.
If you want to put any code it is always better to make it nested.

In C++ and C# are multiple condition checks performed in a predetermined or random sequence?

Situation: condition check in C++ or C# with many criteria:
if (condition1 && condition2 && condition3)
{
// Do something
}
I've always believed the sequence in which these checks are performed is not guaranteed. So it is not necessarily first condition1 then condition2 and only then condition3. I learned it in my times with C++. I think I was told that or read it somewhere.
Up until know I've always written secure code to account for possible null pointers in the following situation:
if ((object != null) && (object.SomeFunc() != value))
{
// A bad way of checking (or so I thought)
}
So I was writing:
if (object != null)
{
if (object.SomeFunc() != value)
{
// A much better and safer way
}
}
Because I was not sure the not-null check will run first and only then the instance method will be called to perform the second check.
Now our greatest community minds are telling me the sequence in which these checks are performed is guaranteed to run in the left-to-right order.
I'm very surprised. Is it really so for both C++ and C# languages?
Has anybody else heard the version I heard before now?
Short Answer is left to right with short-circuit evaluation. The order is predictable.
// perfectly legal and quite a standard way to express in C++/C#
if( x != null && x.Count > 0 ) ...
Some languages evaluate everything in the condition before branching (VB6 for example).
// will fail in VB6 if x is Nothing.
If x Is Not Nothing And x.Count > 0 Then ...
Ref: MSDN C# Operators and their order or precedence.
They are defined to be evaluated from left-to-right, and to stop evaluating when one of them evaluates to false. That's true in both C++ and C#.
I don't think there is or has been any other way. That would be like the compiler deciding to run statements out of order for no reason. :) Now, some languages (like VB.NET) have different logical operators for short-circuiting and not short-circuiting. But, the order is always well defined at compile time.
Here is the operator precedence from the C# language spec. From the spec ...
Except for the assignment operators,
all binary operators are
left-associative, meaning that
operations are performed from left to
right. For example, x + y + z is
evaluated as (x + y) + z.
They have to be performed from left to right. This allows short circuit evaluation to work.
See the Wikipedia article for more information.

Categories