If Condition of VB.NET (IIf) is not equal by C# (?:) - 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.

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# bitwise negation ! check equivalent

Given the following C++ Code:
void Check(DWORD64 ptr)
{
if ( ! (ptr & 0x8000000000000000) )
return;
}
In C# this results in the following Error:
CS0023 Operator '!' cannot be applied to operand of type 'ulong'
How do I bitwise check the ptr parameter in C#?
Comparing to not 0?
void Check(ulong ptr)
{
if ((ptr & 0x8000000000000000) != 0)
return;
}
or checking for 0?
void Check(ulong ptr)
{
if ((ptr & 0x8000000000000000) == 0)
return;
}
Googleing for this questions leads to all sorts of answers on different bitwise operations but I couldn't find an answer for this specific negation with exclemation mark.
When operator ! "logical not" is applied to a numeric value in C or C++, it produces a result as follows:
1 if its operand is zero
0 otherwise
C's conditional statement if interprets 0 as "false" and any non-zero value, including 1, as "true". Therefore, your second option is correct.
The second one. C++ would treat any nonzero value as true, so the ! check on an integer was effectively equivalent to !(value != 0) or (value==0)

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 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.

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