mardi 7 juillet 2015

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 ?

Aucun commentaire:

Enregistrer un commentaire