Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is IIF in C#? [duplicate]

Tags:

c#

.net

vb.net

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#?

like image 635
abhi Avatar asked Aug 27 '10 18:08

abhi


People also ask

What is the IIf function in access?

The Microsoft Access iif function returns one value if a specified condition evaluates to TRUE, or another value if it evaluates to FALSE.

What is the use of IIf in VB net?

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.


2 Answers

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;
}
like image 78
JaredPar Avatar answered Sep 30 '22 04:09

JaredPar


Yep, it's the question mark (A.K.A the conditional operator).

intCurrency = or.Fields["Currency"].Value == "USD" ? 100 : 0;
like image 43
josh3736 Avatar answered Sep 30 '22 05:09

josh3736