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"
Related
I'm making human to animal year converter.
My code:
if (comboBox2.SelectedIndex == 1 || 2)
{
comboBox3.Visible = true;
}
I get the following error :
Operator '||' cannot be applied to operands of type 'bool' and 'int'
Problem: Your if condition, which you thought would resolve to:
comboBox2.SelectedIndex == 1 || comboBox2.SelectedIndex == 2
Actually resolves to:
(comboBox2.SelectedIndex == 1) || (2)
Reason: The equality operator (==) has more precedence than the conditional OR operator (||).
More info: MSDN: C# Operator Precedence and Associativity
The first part of (comboBox2.SelectedIndex == 1) || (2) returns a value of type bool while the second of type int.
Hence the error:
Operator '||' cannot be applied to operands of type 'bool' and 'int'
Resolution: You should clearly specify the condition as:
comboBox2.SelectedIndex == 1 || comboBox2.SelectedIndex == 2
You can't use the above expression like this
if (comboBox2.SelectedIndex == 1 || 2)
{
comboBox3.Visible = true;
}
You have to use it in the following way:
if (comboBox2.SelectedIndex == 1 || comboBox2.SelectedIndex == 2 )
{
comboBox3.Visible = true;
}
You are trying to check make an OR operation on boolean (left side, comparison operator) and an integer number (right side, just a number).
OR (||) has to be applied on two booleans values.
So you should do something like that:
if (comboBox2.SelectedIndex == 1 || comboBox2.SelectedIndex == 2)
{
comboBox3.Visible = true;
}
Reference: http://msdn.microsoft.com/en-gb/library/6373h346.aspx#fbid=5K95u5HbB8E
The logical or operator (||) is used to do a logical or on boolean values.
In a natural language like english you say
"It should be blue or red"
but what you really mean is
"It should be blue or it should be red"
Same thing with computers. They can only evaluate on complete expressions, not on shortcuts.
Try the following instead:
if (comboBox2.SelectedIndex == 1 || comboBox2.SelectedIndex==2)
{
comboBox3.Visible = true;
}
The first part of the if condition evaluates a boolean value if the index is 1, the second part evaluates to a boolean value if the index is 2. The logical or operator combines these two values and return s true if one of the or both are true.
you are doing it wrong because for second condition after OR Operator you are missing first operand . try this code
if (comboBox2.SelectedIndex == 1 || comboBox2.SelectedIndex==2)
{
comboBox3.Visible = true;
}
(comboBox2.SelectedIndex == 1 || comboBox2.SelectedIndex == 2)
Use this if (comboBox2.SelectedIndex == 1 || comboBox2.SelectedIndex==2)
instead of if (comboBox2.SelectedIndex == 1 || 2)
|| Operator
The conditional-OR operator (||) performs a logical-OR of its bool operands. If the first operand evaluates to true, the second operand isn't evaluated. If the first operand evaluates to false, the second operator determines whether the OR expression as a whole evaluates to true or false.
if (comboBox2.SelectedIndex == 1 || comboBox2.SelectedIndex==2)
{
comboBox3.Visible = true;
}
To make it somewhat more elegant and flexible, have this:
comboBox3.Visible = (new[] { 1, 2 }).Contains(comboBox2.SelectedIndex);
This way you can add as many possible values as you want without adding another condition for each.
If you don't want to set the visibility to false but just to true when condition is met, you can have:
comboBox3.Visible = (new[] { 1, 2 }).Contains(comboBox2.SelectedIndex) ? true : comboBox3.Visible;
Logical operators can be used only between two boolean values. But in your case the first one is an Boolean value and the second one is taken as an integer as you have not written any condition there.
So, write the following statement
if ((comboBox2.SelectedIndex == 1) || (comboBox2.SelectedIndex==2))
{
comboBox3.Visible = true;
}
I want to say if this property is (Null OR Equals "" OR contains "ImageNotAvailable") Then go ahead and do something. But when I try to use the code below, I get an object reference error. I was hoping by putting (Publisher.ThumbnailURL == null) at the beginning of the test, the other tests would be ignored, but I get error above.
if ((Publisher.ThumbnailURL == null) | (Publisher.ThumbnailURL == "") | (Publisher.ThumbnailURL.Contains("ImageNotAvailable")))
I can simply split these up into "If Else's" but is there a way to specify that if the first test is null, don't try and figure out the rest of the If statement which will cause it to error
Use || instead of |:
if ((Publisher.ThumbnailURL == null) || (Publisher.ThumbnailURL == "") || (Publisher.ThumbnailURL.Contains("ImageNotAvailable")))
|| Operator
The conditional-OR operator (||) performs a logical-OR of its bool
operands, but only evaluates its second operand if necessary.
Note that you could also use string.IsNullOrEmpty as commented by Raphaël Althaus:
if (string.IsNullOrEmpty(Publisher.ThumbnailURL) || Publisher.ThumbnailURL.Contains("ImageNotAvailable"))
Yep, use || to evaluate the expression as early as possible, also, using String.IsNullOrEmpty would make the statement more brief:
if (String.IsNullOrEmpty(Publisher.ThumbnailURL) || (Publisher.ThumbnailURL.Contains("ImageNotAvailable")))
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).
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.
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...