Merging nested If in C# (Short Circuit Keywords in C#) - c#

Is it possible to merge the following statement:
if (a != null)
{
if (a.Count > 5)
{
// Do some stuff
}
}
to just 1 If statement and make it not to check the second condition when the first one is not satisfied. (like AndAlso keyword in VB.NET). something like:
if (a != null /* if it is null, don't check the next statement */ &&& a.Count > 5)
{
// Do some stuff
}

Simply:
if ((a != null) && (a.Count > 5)) {
// ...
}
In C#, the && operator short-circuits, meaning it only evaluates the right-hand expression if the left-hand expression is true (like VB.NET's AndElse).
The And keyword you are used to in VB.NET does not short-circuit, and is equivalent to C#'s & (bitwise-and) operator.
(Similarly, || also short-circuits in C#, and VB.NET's Or is like C#'s |.)

if ((a != null) && (a.Count > 5)) // Parentheses are nice, but not necessary
{
// Excitement goes here
}
In C#, && is indeed a "short circuit" operator — if the expression to its left is false, the expression to its right will not be evaluated.

You need the && operator to short-circuit the if statement:
if (a != null && a.Count > 5)
{
// Execute code
}
So, if a is null then there is no need to evaluate the second condition for the if statement to return a value of false and therefore not execute the code in the block.

Related

Does an if statement return immediately when one of the conditions is false [duplicate]

This question already has answers here:
Difference between eager operation and short-circuit operation? (| versus || and & versus &&)
(7 answers)
Does the compiler continue evaluating an expression where all must be true if the first is false?
(6 answers)
Closed 3 years ago.
I'm curious about optimization opportunities by changing the order of conditions in an if statement.
Given the example below, if x is false, will the if statement try to execute the other two conditions. If it won't, should I include them in an if branch. Also at what order do they execute. Is it left to right or is it right to left?
if (x && y && z)
{
// ...
}
The check is done from left to right - if X is false, the if statement will return right away.
Think about code with null checking, for example. You would write
if(list != null && list.count > 10) {
// do something
}
but not
if(list.count > 10 && list != null) {
// the null check here does not help you
}
In c#,
if(X&y&z){}
using logical operator & always evaluates all statements.
On the contrary, if you use conditional logical operators && for conditional logical AND and || for conditional logical OR, statements are evaluated left to right and right hand statements are evaluated only if necessary.
if (x & y) {}
always evaluates both x and y, while
if (x && y) {}
Only evaluates y if x is false.
For reference check:
Microsoft .NET documentation on Boolean logical operators

In what order are boolean expressions evaluated

I have been looking for an explanation for the order in which boolean expressions are evaluated but cannot find one.
Take a look at this statement :
if (locClsTanken.PlaceID == -1 && locRwF.PlaceID > -1 || locClsTanken.DagPrijs == 0)
How is this evaluated.
will it be like this :
if ((locClsTanken.PlaceID == -1 && locRwF.PlaceID > -1) || locClsTanken.DagPrijs == 0)
or like this :
if (locClsTanken.PlaceID == -1 && (locRwF.PlaceID > -1 || locClsTanken.DagPrijs == 0))
Is there some documentation about this I dont know the correct search term because english is not my language.
I know I can test it but I would like to find the documentation about this so I can fully understand it
&& has higher precedence than ||, so
locClsTanken.PlaceID == -1 && locRwF.PlaceID > -1 || locClsTanken.DagPrijs == 0
is evaluated as
(locClsTanken.PlaceID == -1 && locRwF.PlaceID > -1) || locClsTanken.DagPrijs == 0
Note that && and || are also short-circuited so evaluation of the right-hand operand only occurs if that could change the result following the evaluation of the left-hand one.
Reference: https://msdn.microsoft.com/en-gb/library/aa691323(v=vs.71).aspx
The expression are readed from left to right in addition to that the && has higher precedence than ||.So in your case it's would be like
if ((locClsTanken.PlaceID == -1 && locRwF.PlaceID > -1) || locClsTanken.DagPrijs == 0)
And the technical therm that you're looking for is
Operators Precedence take a look to this link:Operators Precedence
In C# the compiler moves from left to right, meaning it will evaluate the left most expression first (in your case that is locClsTanken.PlaceID == -1)
Also, && has higher priority than || --> gets evaluated first
However, what might confuse you is how the compiler handels the && and ||. There is a difference between & and &&.
& means both expressions have to be true and both expressions are evaluated. However, && only causes one expression to be evaluated first. If the first expression fails, then the second one isn't even evaluated, because in order for && to be true both expressions need to be true. If the first one already fails && is always false --> && is faster than & and more "inteligent"

C# string.length > 0 seen as boolean

I am new to C# but not to programming. When I compare the lengths of two strings in the code below, I get the error:
Operator '&' cannot be applied to operands of type 'bool' and 'int'
Apparently string1.Length > 0 is seen as a boolean in this context.
How should I perform this comparison?
if (string1.Length > 0 & string2.Length = 0)
{
//Do Something
}
The reason for the error is because you have written = when you meant ==. In C#
string1.Length > 0 & string2.Length = 0
means
(string1.Length > 0) & (string2.Length = 0)
The type of the left side is bool and the type of the right side is int, which cannot be &-ed together, hence the error. Of course even if you managed to get past that, Length cannot be the target of an assignment either.
Use == to test for equality. = is assignment.
Consider also using && instead of &. The meaning of x & y is "evaluate both, the result is true if both are true and false otherwise". The meaning of x && y is "evaluate the left side; if it is false then the result is false so do not evaluate the right side. If the left side is true then proceed as & does."
When applied to integers, the & operator in C# is a bitwise AND, not a logical AND. Also = is an assignment, not an equality comparison operator. The string1.Length > 0 expression is indeed an expression of boolean type, while the assignment is integer (because 0 is integer).
What you need is
if (string1.Length > 0 && string2.Length == 0)
You probably meant to do this:
if (string1.Length > 0 && string2.Length == 0)
{
//Do Something
}
In C#, the = operator is just for assignment. The == is used for equality comparisons. You probably also want to use the && operator instead of & (&& will skip the second condition if the first condition evaluates to false).
However, if really want to 'compare the lengths of the strings', you can just do this:
if (string1.Length > string2.Length)
{
//Do Something
}
This will fix your problem.
if(string1.Length > 0 && string2.Length == 0)
I think you want a == for your equality test? C# assignment returns a value (as in C).

Order of operators in IF statement

I often do this when necessary to prevent a null pointer exception:
// Example #1
if (cats != null && cats.Count > 0)
{
// Do something
}
In #1, I've always just assumed that the cats != null needs to be first, because order of operations evaluate from left to right.
However, unlike example #1, now I want to do something if the object is null or if the Count is zero, therefore I'm using logical OR instead of AND:
// Example #2
if (table == null || table.Rows == null || table.Rows.Count <= 0)
{
// Do something
}
Does the order of the logical comparisons matter? Or can I also reverse the order and get the same results, such as in Example #3?
// Example #3
if (table.Rows.Count <= 0 || table.Rows == null || table == null)
{
// Do something
}
(btw, I realize I can rewrite #2 like below, but I think it's messy, and I'm still curious about the OR operators)
// Example #4
if (!(table != null && table.Rows != null && table.Rows.Count > 0))
{
// Do something
}
In the example you provide:
if (table == null || table.Rows == null || table.Rows.Count <= 0)
{
// Do something
}
...neither table.Rows, nor table.Rows.Count, will be dereferenced if tables is null.
That's because, with C# logical operators, order of operations matter. C# logical operators are short-circuiting - they evaluate from left to right, and if any result causes the rest of the expression to be moot, the rest of the expression will not be evaluated.
Consider this code:
bool A()
{
return false;
}
bool B()
{
return true;
}
//...
if (A() && B())
{
// do something
}
For an AND clause to be true, all elements must be true. However, A() returns false, and the runtime (or maybe the compiler here, in an optimization step, but let's not worry about that...) won't evaluate B() at all.
The same holds true for OR (||) expressions. If any element in the clause is true, evaluated left to right, the rest of the clause won't be executed.
Yes, the short-circuiting happens in both cases, the only difference being that && stops if the LHS is false (because the overall expression must then be false) while || stops if the LHS is true (because the overall expression must be true).
The first two examples in your question are correct, the third will throw an exception if table or table.Rows are null.
You should note that not all C# logical operators exhibit short-circuting behaviour (as was indicated above).
You are using the Conditional-AND operator (&&) and that does short-circuit. However the AND (&) operator is exactly the same as the Conditional-AND without the short-circuit.
The same is true for the OR and Conditional-OR operators.
For Example:
//This will throw if cats is null, whatever order.
if (cats != null & cats.Count > 0){ }
//This will not. Due to short-circuting.
if (cats != null && cats.Count > 0){ }
The first construction is not the same as the second one. The first one is to use when you want to not do anything when the reference is null or Count is zero. The second construction would DO something when it is null or the count is zero... To make the second one the same as the first you would need to write:
if (table == null || table.Rows == null || table.Rows.Count <= 0 || )
{}
else
{
// Do something
}
And order does matter, even in the second one as you wrote it, it would crash if table was null when it tried to evaluate table.Rows.
Order matters. Its all about short circuiting. For ands, the first false it hits it stops evaluating, for ORs it stops as soon as it hits a true.
It will short circuit after the first evaulation and that is why you dont get the null pointer exception.
When you think about it think insert null for each object.
if (null== null || null.Rows == null || null.null.Count <= 0)
{
// Do something
}
Then evaluate each boolean
if( true || null.Rows == null || null.null.Count <=0)
If you see true that means stop. If you hit a "null". statement you will crash.
Example to illustrate a crash
if (null.null.Count <= 0 || null.Rows == null || null== null)
{
// CRASH... Do something
}
Order does not matter.
Clarification:
The order you place the statements in the IF statement will not affect whether or not the IF statement is gone into...and thus the result.
As another poster pointed out, it will however affect which ones are evaluated, but this doesn't affect the bottom line AFAIK.
Edit #JonHanna
I guess I looked at this from the perspective that the OP stated he is checking for NPE's prior when required (see the first line of his post). So if his code doesn't produce runtime errors, then order means nothing. I can't imagine why anyone would code an IF statement with a thought process of "if this IF statement causes a NPE" then it won't get evaluated...

OR, AND Operator

Newbie question.
How to calculate the value of the formula A f B, where f - the binary function OR or AND?
There is a distinction between the conditional operators && and || and the boolean operators & and |. Mainly it is a difference of precendence (which operators get evaluated first) and also the && and || are 'escaping'. This means that is a sequence such as...
cond1 && cond2 && cond3
If cond1 is false, neither cond2 or cond3 are evaluated as the code rightly assumes that no matter what their value, the expression cannot be true. Likewise...
cond1 || cond2 || cond3
If cond1 is true, neither cond2 or cond3 are evaluated as the expression must be true no matter what their value is.
The bitwise counterparts, & and | are not escaping.
Hope that helps.
Logical OR is ||, logical AND is &&.
If you need the negation NOT, prefix your expression with !.
Example:
X = (A && B) || C || !D;
Then X will be true when either A and B are true or if C is true or if D is not true (i.e. false).
If you wanted bit-wise AND/OR/NOT, you would use &, | and ~. But if you are dealing with boolean/truth values, you do not want to use those. They do not provide short-circuit evaluation for example due to the way a bitwise operation works.
if(A == "haha" && B == "hihi") {
//hahahihi?
}
if(A == "haha" || B != "hihi") {
//hahahihi!?
}
I'm not sure if this answers your question, but for example:
if (A || B)
{
Console.WriteLine("Or");
}
if (A && B)
{
Console.WriteLine("And");
}
Use '&&' for AND and use '||' for OR, for example:
bool A;
bool B;
bool resultOfAnd = A && B; // Returns the result of an AND
bool resultOfOr = A || B; // Returns the result of an OR
If what interests you is bitwise operations look here for a brief tutorial : http://weblogs.asp.net/alessandro/archive/2007/10/02/bitwise-operators-in-c-or-xor-and-amp-amp-not.aspx .bitwise operation perform the same operations like the ones exemplified above they just work with binary representation (the operation applies to each individual bit of the value)
If you want logical operation answers are already given.
&& it's operation return true only if both operand it's true which implies
bool and(bool b1, bool b2)]
{
if(b1==true)
{
if(b2==true)
return true;
}
return false;
}
|| it's operation return true if one or both operand it's true which implies
bool or(bool b1,bool b2)
{
if(b1==true)
return true;
if(b2==true)
return true;
return false;
}
if You write
y=45&&34//45 binary 101101, 35 binary 100010
in result you have
y=32// in binary 100000
Therefore, the which I wrote above is used with respect to every pair of bits
many answers above, i will try a different way:
if you are looking for bitwise operations use only one of the marks like:
3 & 1 //==1 - and
4 | 1 //==5 - or

Categories

Resources