Using &= on boolean values in C# - c#

I have a method in C# called SendEvent that returns a bool which represents if it was successful or not. I want to loop through a number of objects and call SendEvent on them all, and in the end, have a result variable that is a bool, that is true if all SendEvent calls succeeded, and false if at least one failed.
At first I did this:
bool result = true;
for (int i = 0; i < myObjects.Length; i++)
{
result = result && myObjects[i].SendEvent();
}
But that will cause that the SendEvent will not be called on subsequent objects if one fails, as the right hand side of the && operator won't be executed if result is false.
So I turned it around, to:
bool result = true;
for (int i = 0; i < myObjects.Length; i++)
{
result = myObjects[i].SendEvent() && result;
}
But I found that somewhat ugly. Can I use the bitwise &= operator to always execute the SendEvent call, and set the value of result, like this?
bool result = true;
for (int i = 0; i < myObjects.Length; i++)
{
result &= myObjects[i].SendEvent();
}
How does the &= work on boolean values? Will it execute both sides of the operator? What will end up in the result variable?

As you can read here, both & and && are defined for bools as "logical and", but && will short-circuit: in case the first operand is false the expression on the right will not be evaluated. Regardless what the outcome of the expression on the right is, the result of the && expression will remain false. This is usually a "performance hack" in the first place, but if the right expression has side-effects, could throw an exception, etc., it is something you have to take into account. The same happens for the || operator if the first operand is true.
So if you want to evaluate both sides first, you can indeed use:
result = result & myObjects[i].SendEvent();
or shorter:
result &= myObjects[i].SendEvent();
Background
As is written in the language specifications:
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.
Note that there is no &&= operator (at least at the time I am writing this). This looks reasonable since usually with an ..= operator, you would expect that the operand is first evaluated and then some operation is done on the variable to the left. Of course it is all a matter of style and taste, but I would reason that a hypothetical &&= does not give "enough hints" that the right operand will not be called in all cases.

As a LINQ lover, I would do it like:
var result = (myObjects.Count(obj => obj.SendEvent()) == myObjects.Length);
In case you want to break the loop on the first false value, it coud be:
var result = myObjects.All(obj => obj.SendEvent());

Related

Is it safe to assume if-and statements will always break if the first condition is false? [duplicate]

This question already has answers here:
Usage of '&' versus '&&'
(4 answers)
Closed 1 year ago.
If I have
if (false && true)
...
can I be sure that every computer/compiler/whatever will do the shortcut that ignores the second condition? In my implementation, the second condition assumes that the first is true, otherwise it will cause a fatal error. For example:
if (Foobar is BoolContainer && Foobar.BoolVar)
...
where BoolContainer is an example class with a boolean property BoolVar.
MSDN states(https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators):
The conditional logical AND operator &&, also known as the "short-circuiting" logical AND operator, computes the logical AND of its operands. The result of x && y is true if both x and y evaluate to true. Otherwise, the result is false. If x evaluates to false, y is not evaluated.
So your assumption is correct. Though you should be careful when you use &:
The & operator computes the logical AND of its operands. The result of x & y is true if both x and y evaluate to true. Otherwise, the result is false.
The & operator evaluates both operands even if the left-hand operand evaluates to false, so that the operation result is false regardless of the value of the right-hand operand.
You might get unwanted evaluation when you use &.
There is an extreme edge case where && won't necessarily do what you expect. You won't experience this in normal code. ;)
In the below code both booleans will output as True, but if you && them the result will (on some versions of .NET, but not all) not be True (because true2 is an "unusual" true).
Again, this is not something you will ever experience in real life.
namespace MyNamespace
{
using System;
using System.Runtime.InteropServices;
namespace Work
{
[StructLayout(LayoutKind.Explicit)]
public struct HackedBoolean
{
[FieldOffset(0)] public int value;
[FieldOffset(0)] public bool boolean;
public bool GetBool(int seed)
{
value = seed;
return boolean;
}
}
public class MyClassCS
{
public static void Main(string[] args)
{
var hacked = new HackedBoolean();
var true1 = hacked.GetBool(1);
var true2 = hacked.GetBool(2);
Console.WriteLine(true1);
Console.WriteLine(true2);
Console.WriteLine(true1 && true2);
Console.WriteLine(true1 == true2);
Console.ReadLine();
}
}
}
}
Yes it is safe.
If you want both sides to be evaluated you can use & instead of &&.
Otherwise it will skip second condition in this case.
As per the documentation of Conditional Logical ANN operator && on MSDN condition using && operator evaluates to true only when all the conditions evaluates to true.
If any of the conditions evaluates to false, the entire evaluations results as false.
while evaluating the conditions from left to right, next condition is not evaluated if the previous one evaluates to false.
Yes, it is guaranteed by the language specification:
The operation x && y corresponds to the operation x & y, except that y is evaluated only if x is not false.
In my experience it is a very common idiom for the second part of a short-circuiting conditional expression like this to rely on this behavior.
You might be wondering about why it says "not false" instead of "true". For a bool type, these two are equivalent. At first I thought it was because bool? had a lifted operator to deal with null, but this is not the case. But you can do something similar with a type that overloads the true, false, &, and | operators, and in fact the spec provides the DBBool example struct which does just that.

C#: Compiler optimization, function calls, and Boolean expression short-circuiting

Let's assume that we have the following expensive functions:
bool ExpensiveOp1() { ... }
bool ExpensiveOp2() { ... }
bool ExpensiveOp3() { ... }
Also, to keep it simple, assume that none of them have side effects.
I know that C# can short-circuit if ExpensiveOp1 or ExpensiveOp2 returns false in the following expression:
return ExpensiveOp1() && ExpensiveOp2() && ExpensiveOp3();
However, is the compiler smart enough to (for lack of a better term) inline the function calls and take advantage of short-circuiting if I write the code this way?
var x = ExpensiveOp1();
var y = ExpensiveOp2();
var z = ExpensiveOp3();
return x && y && z;
No, and for a good reason. The compiler doesn't know if any of your operations have side effects, so if you run them outside of a boolean short circuiting situation it runs them in case there are side effects you want.

Does combining short-circuiting operators with regular operators change the result of the expression?

I've always believed that using conditional boolean operators (a.k.a. short-circuiting) in stead of regular boolean operators doesn't affect the outcome of an expression.
var result = true | false & false;
has the same result as
var result = true || false && false
Both expressions result in true.
But what if I would mix regular and conditional operators?
var result1 = true || false & false;
var result2 = true | false && false;
What would you expect? I would expect these to still return true. But that isn't the case. Result2 will be false!
I know this is because of the operator precedence. The precedence order is & | && ||. This seems counter intuitive to me. I'd expect an order of & && | ||, in which case all results would be the same (I think).
So I guess my real question isn't if short-circuiting can change the result. The question is why the order of precedence is such that short-circuiting can change the result.
var result2 = true | false && false;
Is calculated as:
var result2 = (true | false) && false;
Because | comes before &&. Now (true | false) evaluates to true, and true && false is false.
As for the why, see this question:
The && and || operators were added later for their "short-circuiting" behavior. Dennis Ritchie admits in retrospect that the precedence of the bitwise operators should have been changed when the logical operators were added. But with several hundred kilobytes of C source code in existence at that point and an installed base of three computers, Dennis thought it would be too big of a change in the C language...
The precedence of the operators in question seems to be copied directly from the precedence in the C (and C++) programming language.
Now in C, they don't use distinct types for integers and booleans. For example they could write:
if (i | j && x > 0) // cf. the result2 of your question
and this should mean "the integers i and j bitwise or'ed gives something nonzero AND the number x is positive". So | and & are supposed to be mostly used when the operands are thought of as integers (many-bit numbers), and || and && are supposed to be mostly used when the operands are thought of as booleans.
So it might seem natural in C that | binds more strictly than &&.
In C# we have a higher degree of type safety, and there are no conversions from Int32 to Boolean or from Boolean to Int32. Therefore it is no longer possible to "mix" things, and the precedence no longer feels natural.
I guess in theory in C#, one could make the operator
public static bool operator |(bool b, bool c)
have a different precedence than the operator
public static int operator |(int i, int j)
but it wouldn't really make things better?
I think it's very rare that people use boolean non-short-circuit operators like | and short-circuit operators like && in the same expression, but when they do, they should either be very careful about precedence, or just put the parenthesis () there (it will also make the intention more clear).
The & and | operators evaluate both arguments (which could involve calling a method) and then return the result of the and- or or-operation.
The && and || operators only evaluate their arguments to the point where the final result is determined completely.
For example:
true | SomeMethod() and
false & SomeMethod() calls the SomeMethod() function
true || SomeMethod() and
false && SomeMethod() don't.
trueand false in this example could also be variables of course, I simply used constant to make the example easier to understand.

Problem with operator &&

Considering the following code
public bool GetFalse()
{
return false;
}
public bool GetTrue()
{
return true;
}
How can I force this expression GetFalse() && GetTrue() to execute second Method?
Try with:
GetFalse() & GetTrue()
You can't because the logical AND operator short circuits. In the general case it is a good idea to avoid side effects from expressions like that, although there are perfectly valid uses (i.e., if( someObj != null && someObj.Value == whatever ). You could use the bitwise and operator (&) which does not short circuit, but again, I wouldn't do that.
You should split those two method calls into variables first and then perform the check if you need them both to execute.
bool first = SomeMethodCall();
bool second = SomeMethodThatMustExecute();
if( first && second )
{
// ...
}
Use the non-short circuiting version (also known as the bit-wise AND when not working with Boolean values):
GetFalse() & GetTrue();
This is an optimization issue. Since the first method called in the expression is false, the entire expression cannot be true, so the second method in the expression is not called. If it is necessary to call this for a side effect (bad practice to rely on a side effect, but YMMV), something like this should be used:
x = GetFalse();
y = GetTrue();
if (x && y) ...
Assuming that your actual functions perform some specific tasks and return a value indicating (for example) success or failure I would prefer to see this written as
bool fooResult = DoFoo();
bool barResult = DoFar();
And then you can use fooResult && barResult in your code.

What is the difference between & and && operators in C#

I am trying to understand the difference between & and &&operators in C#. I searched on the internet without success. Can somebody please explain with an example?
& is the bitwise AND operator. For operands of integer types, it'll calculate the bitwise-AND of the operands and the result will be an integer type. For boolean operands, it'll compute the logical-and of operands. && is the logical AND operator and doesn't work on integer types. For boolean types, where both of them can be applied, the difference is in the "short-circuiting" property of &&. If the first operand of && evaluates to false, the second is not evaluated at all. This is not the case for &:
bool f() {
Console.WriteLine("f called");
return false;
}
bool g() {
Console.WriteLine("g called");
return false;
}
static void Main() {
bool result = f() && g(); // prints "f called"
Console.WriteLine("------");
result = f() & g(); // prints "f called" and "g called"
}
|| is similar to && in this property; it'll only evaluate the second operand if the first evaluates to false.
Of course, user defined types can overload these operators making them do anything they want.
Strongly recommend this article from Dotnet Mob : http://codaffection.com/csharp-article/short-circuit-evaluation-in-c/
-&& is short-circuit logical operator
For AND operations if any of the operand evaluated to false then total expression evaluated to false, so there is no need to evaluate remaining expressions, similarly in OR operation if any of the operand evaluated to true then remaining evaluation can be skipped
-& operator can be used as either unary or binary operator. that is, unary & can be used to get address of it’s operand in unsafe context.
& can be used on either integral types (like int, long etc.) or on bool.
When used on an integral type, it performs a bitwise AND and gives you the result of that. When used on a bool, it performs a logical AND on BOTH its operands and gives you the result.
&& is not used as a bitwise AND. It is used as a logical AND, but it does not necessarily check both its operands. If the left operand evaluates to false, then it doesn't check the right operand.
Example where this matters:
void Action()
{
string name = null;
if(name != null && name.EndsWith("ack"))
{
SomeOtherAction();
}
}
If name is null, then name.EndsWith("ack") will never get executed. It is smart enough to know if the left operand is false, then the right operand doesn't need to be evaluated (aka "short-circuiting"). That's good because calling a method on null will throw a NullReferenceException.
If you changed it into if(name != null & name.EndsWith("ack")), both sides would get evaluated and it would throw a NullReferenceException.
One detail: & can also be a unary operator (so it has one operand) in an unsafe context. It will give the address of a value or object. It's not important though, as most people don't ever have to touch this part of the language.
Below example and explanation's may help.
Example:
public static bool Condition1()
{
Console.WriteLine("Condition1 is evaluated.");
return false;
}
public static bool Condition2()
{
Console.WriteLine("Condition2 is evaluated.");
return true;
}
1. Logical Operator
& (ampersand) Logical AND operator
| (pipeline) Logical OR operator
Used for ensuring all operands are evaluated.
if(Condition1() & Condition2())
{
Console.WriteLine("This will not print");
//because if any one operand evaluated to false ,
//thus total expression evaluated to false , but both are operand are evaluated.
}
if (Condition2() | Condition1())
{
Console.WriteLine("This will print");
//because any one operand evaluated to true ,
//thus total expression evaluated to true , but both are operand are evaluated.
}
2. Conditional Short Circuit Operator
&& (double ampersand) Conditional AND operator
|| (double pipeline) Conditional OR operator
Used for Skipping the right side operands , Has Side effects so use carefully
if (Condition1() && Condition2())
{
Console.WriteLine("This will not print");
//because if any one operand evaluated to false,
//thus total expression evaluated to false ,
//and here the side effect is that second operand is skipped
//because first operand evaluates to false.
}
if (Condition2() || Condition1())
{
Console.WriteLine("This will print");
//because any one operand evaluated to true
//thus remaining operand evaluations can be skipped.
}
Note:
To get better understanding test it in console sample.
References
dotnetmob.com
wikipedia.org
stackoverflow.com
& is a bitwise operator and && is a logical operator that applies to bool operands.
Easy way to look it is logical & will evaluate both sides of the & regardless if the left side is false, whereas the short-circuit && will only evaluate the right side if the left is true.
d=0;
n=10;
// this throws divide by 0 exception because it evaluates the
// mod even though "d != 0" is false
if ( (d != 0) & (n % d) == 0 )
Console.Writeline( d + " is a factor of " + n);
// This will not evaluate the mod.
if ( (d != 0) && (n % d) == 0 )
Console.Writeline( d + " is a factor of " + n);
The first one is bitwise and the second one is boolean and.
According to - C# 4.0 The Complete Reference by Herbert Schildt
& - Logical AND Operator
| - Logical OR Operator
&& - Short Circuited AND Operator
|| - Short Circuited OR Operator
A simple example can help understand the phenomena
using System;
class SCops {
static void Main() {
int n, d;
n = 10;
d = 2;
if(d != 0 && (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);
d = 0; // now, set d to zero
// Since d is zero, the second operand is not evaluated.
if(d != 0 && (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);
// Now, try the same thing without the short-circuit operator.
// This will cause a divide-by-zero error.
if(d != 0 & (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);
}
}
Here the & operator checks each and every operand and && checks only the first operand.
As you might notice for 'AND' operations any operand which is false will evaluate the whole expression to false irrespective of any other operands value in the expression.
This short circuited form helps evaluate the first part and is smart enough to know if the second part will be necessary.
Running the program will throw a divide-by-zero error for the last if condition where both the operands are checked for & operator and no exception handling is done to tackle the fact that 'd' can be 0 at any point of time.
The same case applies to '|' in C#.
This is slightly different than C or C++ where '&' and '|' were bitwise AND and OR operators. However C# also applies the bitwise nature of & and | for int variables only.
Hai Friend,
The Operator &&(Logical Operator) is used in conditional statements.
For Instance
if(firstName == 'Tilsan' && lastName == 'Fighter')
{
Response.Write("Welcome Tilsan The Fighter!");
}
the Response.Write statement will run only if both variables firstName and lastName match to their condition.
Whereas & (Bitwise Operator)operator is used for Binary AND operations, i.e., if we write:
bool a, b, c;
a = true;
b = false;
c = a & b;
Response.Write(c); // 'False' will be written to the web page
Here first Binary And operation will be performed on variables a and b, and the resultant value will be stored in variable c.

Categories

Resources