I just started using Vb.Net. I'm used to C# syntax. I know that I can do this in C# :
if (x | y)
//Test both
if (x || y)
//Test both unless x is true
In Vb.Net how can I accomplish the same thing considering that :
If x or y Then
//Test both no matter what
In Vb.Net how can I accomplish the same thing?
OrElse
The documentation is here:
http://msdn.microsoft.com/en-us/library/ea1sssb2.aspx
The VB equivalent of && is AndAlso by the way.
In Vb.NET the equivalent is OrElse.
Used to perform short-circuiting logical disjunction on two
expressions.
If x OrElse y Then
Reference: http://msdn.microsoft.com/en-us/library/ea1sssb2(v=vs.71).aspx
Related
I am trying to convert VB.NET code to C#. I have the following:
If IsDataProperty(p) And (p.Name.StartsWith("ref_") = False) Then
...
If I use a decompiler to see what the C# version looks like, I get this:
if (this.IsDataProperty(p) & !p.Name.StartsWith("ref_")) {
...
The AND operator in VB compiled to & C# operator.
Shouldn't the code be with && operator:
if (this.IsDataProperty(p) && !p.Name.StartsWith("ref_")) {
...
Logically speaking, in the VB code, if IsDataProperty(p) is false, the entire statement will be false.
VB.NET has special keywords for short circuiting.
bool valueAnd = conditionA && conditionB;
bool valueOr = conditionA || conditionB;
Dim valueAnd As Boolean = conditionA AndAlso conditionB
Dim valueOr As Boolean = conditionA OrElse conditionB
The equivalent of And in VB.NET really is &. To get C#'s && you should have used "AndAlso" in VB.NET.
https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/andalso-operator
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
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.
Anyway here's my problem I have been modifying a whole C++ program to work in C# and I am pretty much done, I have this If statement in the C++ program.
if(info[i].location & 0x8 ||
info[i].location & 0x100||
info[i].location & 0x200)
{
//do work
}
else
{
return
}
And of course when I do this in C# it gives me a "Operator '||' cannot be applied to operands of type 'int' and 'int'" error.
Any clue on what my problem is, Im guessing that C# has got a way of doing this as I am fairly unfamiliar with these old C operators.
Why it fails
Fundamentally it's the same difference as this:
if (someInteger) // C or C++
vs
if (someInteger != 0) // C#
Basically C# is a lot stricter when it comes to logical operators and conditions - it forces you to have use something which is either bool or convertible to bool.
As an aside, that's also why in C# this isn't just a warning, but a full-blown error:
int x = ...;
if (x = 10) // Whoops - meant to be == but it's actually an assignment
If you see comparisons this way round:
if (10 == x)
That's usually developers trying to avoid typos like the above - but it's not needed in C# unless you're really comparing against constant bool values.
Fixing the problem
I suspect you just need:
if (((info[i].location & 0x8) != 0)) ||
((info[i].location & 0x100) != 0)) ||
((info[i].location & 0x200) != 0)))
It's possible that you don't need all of those brackets... but another alternative is just to use one test:
if ((info[i].location & 0x308) != 0)
After all, you're just testing whether any of those three bits are set...
You should also consider using a flags-based enum:
[Flags]
public enum LocationTypes
{
Foo = 1 << 3; // The original 0x8
Bar = 1 << 8; // The original 0x100
Baz = 1 << 9; // The original 0x200
}
Then you could use:
LocationTypes mask = LocationTypes.Foo | LocationTypes.Bar | LocationTypes.Baz;
if ((info[i].location) & mask != 0)
Or using Unconstrained Melody:
LocationTypes mask = LocationTypes.Foo | LocationTypes.Bar | LocationTypes.Baz;
if (info[i].location.HasAny(mask))
It's pretty much exactly what it says: in C#, || is a logical-only operator and so cannot work on int. You can replace || with | (the bitwise-or which works on ints), but then the entire expression will need to be converted to boolean by comparing it to zero, because in C# the if-statements require a boolean.
Alternatively, you can replace info[i].location & 0x8 with (info[i].location & 0x8 != 0).
When comparing to a minimum or maximum of two numbers/functions, does C# short-circuit if the case is true for the first one and would imply truth for the second? Specific examples of these cases are
if(x < Math.Max(y, z()))
and
if(x > Math.Min(y, z()))
Since Math.Max(y, z()) will return a value at least as large as y, if x < y then there is no need to evaluate z(), which could take a while. Similar situation with Math.Min.
I realize that these could both be rewritten along the lines of
if(x < y || x < z())
in order to short-circuit, but I think it's more clear what the comparison is without rewriting. Does this short-circuit?
As others have pointed out, the compiler knows nothing about the semantics of Min or Max that would allow it to break the rule that arguments are evaluated before the method is called.
If you wanted to write your own, you could do so easily enough:
static bool LazyLessThan(int x, int y, Func<int> z)
{
return x < y || x < z();
}
and then call it
if (LazyLessThan(x, y, z))
or
if (LazyLessThan(x, y, ()=>z()))
Or for that matter:
static bool LazyRelation<T>(T x, T y, Func<T> z, Func<T, T, bool> relation)
{
return relation(x, y) || relation(x, z());
}
...
if (LazyRelation(x, y, ()=>z, (a,b)=> a < b)))
No, it doesn't short circuit and z() will always be evaluated. If you want the short circuiting behavior you should rewrite as you have done.
Math.Min() and Math.Max() are methods just like any other. They have to be evaluated in order to return the value which will be used as the second argument in the comparison. If you want short-circuiting then you will have to write the condition using the || operator as you have demonstrated.
(Nothing particularly new to add, but I figured I'd share the results of a test I ran on it.)
Math.Max() could easily be inlined by the CLR's just-in-time compiler and from there I was curious whether it might further optimize the code in such a way that it is short-circuited.
So I whipped up a microbenchmark that evaluates the two expressions 1,000,000 times each.
For z(), I used a function that calculates Fib(15) using the recursive method. Here are the results of running the two:
x < Math.Max(y, z()) : 8097 ms
x < y || x < z() : 29 ms
I'm guessing the CLR won't transform the code in any way that prevents method calls from executing, because it doesn't know (and doesn't check to see if) the routine has any side effects.
No, it doesnt short circuit, at least at the C# compiler level. Math.Min or Math.Max are two ordinary static method calls and the compiler will not optimize in that sense.
The order of evaluation of the code will be: z(), Math.Max, x > ...
If you really want to make sure, check out the IL code.