Why does the AND statement in VB compile to a & operator? - c#

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

Related

If Condition of VB.NET (IIf) is not equal by C# (?:)

The IIf function in VB.NET :
IIf(condition As Boolean, TruePart As Object, FalsePart As Object) As Object
exactly is not equal by C# conditional operator (?:) :
condition ? first_expression : second_expression;
When I convert some codes from c# to vb.net, I understand that converted codes not work correctly because in vb.net if conditional are evaluated both of the true and false parts before the condition is checked!
For example, C#:
public int Divide(int number, int divisor)
{
var result = (divisor == 0)
? AlertDivideByZeroException()
: number / divisor;
return result;
}
VB.NET:
Public Function Divide(number As Int32, divisor As Int32) As Int32
Dim result = IIf(divisor = 0, _
AlertDivideByZeroException(), _
number / divisor)
Return result
End Function
Now, my c# codes executed successfully but vb.net codes every times that divisor is not equal by zero, runs both of AlertDivideByZeroException() and number / divisor.
Why this happens ?
and
How and with what do I replace the c# if-conditional operator (?:) in VB.net ?
In Visual Basic, the equality operator is =, not ==. All you need to change is divisor == 0 to divisor = 0.
Also, as Mark said, you should use If instead of IIf. From the documentation on If: An If operator that is called with three arguments works like an IIf function except that it uses short-circuit evaluation. Since C# uses short-circuit evaluation, you will want to use If for the same functionality in VB.

Condition if differences in C# and VB

Why does conditional if in VB require not handle the direct cast of the conditions. For example in C# this is just fine...
bool i = false;
i = (1<2)? true:false;
int x = i? 5:6;
But if I wanted the same thing in VB I would have to cast it
Dim i as Boolean = CBool(IIF(1<2, True, False))
Dim x as Integer = CInt(IIF(i, 5, 6))
I don't understand why C# will do the transform and why VB does not. Should I be casting on my C# conditionals eg
bool i = Convert.ToBoolean((1<2)? True: False);
int x = Convert.ToInt32(i? 5:6);
Also, Yes I am aware that IIF returns type object but I would assume that C# does as well as you can return more than just True|False; it seems to me that C# handles the implicit conversion.
IIf is a function and is not equivalent to C#’s ?:, which is an operator.
The operator version has existed for a while in VB.NET, though, and is just called If:
Dim i As Boolean = If(1 < 2, True, False)
… which is, of course, pointless, and should just be written as:
Dim i As Boolean = 1 < 2
… or, with Option Infer:
Dim i = 1 < 2
This code will show you the difference between the IIf function and the If operator. Because IIf is a function, it has to evaluate all of the parameters to pass into the function.
Sub Main
dim i as integer
i = If(True, GetValue(), ThrowException()) 'Sets i = 1. The false part is not evaluated because the condition is True
i = IIf(True, GetValue(), ThrowException()) 'Throws an exception. The true and false parts are both evaluated before the condition is checked
End Sub
Function GetValue As Integer
Return 1
End Function
Function ThrowException As Integer
Throw New Exception
Return 0
End Function

What is = Not(VB) in C#

So say if I have this code
circularProgress1.IsRunning = Not circularProgress1.IsRunning // in VB
how would I make this in C# ?
circularProgress1.IsRunning != circularProgress1.IsRunning // This doesn't work
circularProgress1.IsRunning = !circularProgress1.IsRunning;
= is an assignment and ! is a negation
The != operator is the opposite of the == operator. It returns true when two objects are unequal. Side-note: In VB.NET the assignement- and the equality-operator are both =.
circularProgress1.IsRunning = !circularProgress1.IsRunning.

OR vs || conditions

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

Please explain C# syntax to a vb-er

I have the following code snippet:
// Notify the source (the other control).
if (operation != DropOperation.Reorder) {
e = new DroppedEventArgs()
{
Operation = operation == DropOperation.MoveToHere ? DropOperation.MoveFromHere : DropOperation.CopyFromHere,
Source = src,
Target = this,
DroppedItems = srcItems
};
src.OnDropped(e);
}
I do not understand the
Operation = operation == DropOperation.MoveToHere ? DropOperation.MoveFromHere : DropOperation.CopyFromHere line.
Can someone explain it? For the record...dropOperation is an enum.
Can you give vb syntactical equivalent is all I need.
Seth
The reason it's hard to understand is due to the fact that you're unfamiliar with the ternary operator ?:. Basically what it does is evaluate an expression, and return one of two value depending on whether the evaluation returned true or false.
For example, the following expression will return "true" if the boolean is true, and "false" elsewise:
bool test = false;
string testString = test ? "true" : "false";
It does in fact exist in VB.NET as well - expressed a bit differently though. These two statements in respectively C# and VB.NET are in fact the same
Dim s As String = If(True, "kek", "lol")
string s = true ? "kek" : "lol";
The difference between IIf and the tenary operator is that IIf will always evaluate both the second and third parameter because IIf is a function instead of an operator. For this reason the tenary operator is much to prefer.
Note: The tenary operator was added in VB 9, so if you're using previous versions you'll have to rely on the IIF function for this functionality.
If (operation = DropOperation.MoveToHere) Then
Operation = DropOperation.MoveFromHere
Else
Operation = DropOperation.CopyFromHere
End If
Obligatory wikipedia link. I gave up on mentioning this link in a comment, so here it is in an answer. You can replace uses of the ? operator with calls to the IIF function:
Operation = IIF(operation = DropOperation.MoveToHere, DropOperation.MoveFromHere, DropOperation.CopyFromHere)
Note that they are not strictly equivalent, since the IIF function evaluates both the true and the false case, whereas the ? operator only evaluates the case it returns.
It is sort of equivalent of the IIf function in VB.NET (see Brian's comment):
Operation = IIf(operation = DropOperation.MoveToHere, _
DropOperation.MoveFromHere, _
DropOperation.CopyFromHere)
In C# this is called the conditional operator, and is a sort of shortcut for a simple if/else statement.
This is the conditional operator, it is very similar to VB's IIf function:
Returns one of two objects, depending on the evaluation of an expression.
Public Function IIf( _
ByVal Expression As Boolean, _
ByVal TruePart As Object, _
ByVal FalsePart As Object _
) As Object
In this particular example the IIf function would be written like this:
Operation = IIF((operation = DropOperation.MoveToHere), _
DropOperation.MoveFromHere, _
DropOperation.CopyFromHere)
This is using the ? operator for conditional assignment. This line is basically syntactic sugar for:
// C# expanded example
if (operation == DropOperation.MoveToHere)
{
Operation = DropOperation.MoveFromHere;
}
else
{
Operation = DropOperation.CopyFromHere;
}
Which, in VB, would be equivalent to:
If operation = DropOperation.MoveToHere Then
Operation = DropOperation.MoveFromHere
Else
Operation = DropOperation.CopyFromHere
End If
operation == DropOperation.MoveToHere ? DropOperation.MoveFromHere : DropOperation.CopyFromHere
This is called the ternary operator. It's basically a short way of writing:
if (operation == DropOperation.MoveToHere)
return DropOperation.MoveToHere;
else
return DropOperation.CopyFromHere;
The ?: construct is the ternary operator, basically an inline if (x) y else x. The benefit of the inline is seen here in that it is assigned immediately to a variable. You can't do that with an if statement.
C# Bloggers use the "?" a lot. Look this code:
int Foo(int x, int y){
return x==y? 10: 11;
}
Is equal to:
int Foo(int x, int y){
if (x==y)
return 10;
else
return 11;
}
Just read the well explained Donut's answer!!
("VB-er" I like the term)
It's called the ternary operator. I don't think it exists in VB but it's basically just a shorthand for an if/else.

Categories

Resources