2

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 ?

Behzad
  • 3,502
  • 4
  • 36
  • 63

1 Answers1

6

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.

Jashaszun
  • 9,207
  • 3
  • 29
  • 57