Possible Duplicate:
iif equivalent in c#
I have several lines of code using IIf
in VB and I am trying to convert this code to C#.
Here's an example where I need help:
intCurrency = IIf(or.Fields("Currency").Value = "USD", 100, 0)
How do I change the above line of code to C#? Is there a short-circuit evaluation operator in C#?
The Microsoft Access iif function returns one value if a specified condition evaluates to TRUE, or another value if it evaluates to FALSE.
IIf always evaluates both truepart and falsepart, even though it returns only one of them. Because of this, you should watch for undesirable side effects. For example, if evaluating falsepart results in a division by zero error, an error occurs even if expr is True.
It is close to the C# ternary / conditional operator as several people have suggested but it is not an exact replacement. The C# ternary operator does short circuit evaluation meaning that only the side effect of the evaluated clause occurs. In VB.Net the Iif
function does not implement short circuiting and will evaluate both side effects.
Additionally the Iif
function in VB.Net is weakly typed. It accepts and returns values typed as Object
. The C# ternary operator is strongly typed.
The closest equivalent you can write is the following. Putting the values into the arguments forces the evaluation of their side effects.
public static object Iif(bool cond, object left, object right) {
return cond ? left : right;
}
Or slightly more usable
public static T Iif<T>(bool cond, T left, T right) {
return cond ? left : right;
}
Yep, it's the question mark (A.K.A the conditional operator).
intCurrency = or.Fields["Currency"].Value == "USD" ? 100 : 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With