TechTalk - Ternary Operator : Short hand If Else Statement

The ternary operator is an operator that takes three arguments. The first argument being a comparison argument, the second is the result upon a TRUE comparison (from the frist argument), and the third is the result upon a FALSE comparison. It is a shortened way of writing an if-else statement.

In the C programming language, these two if-else statements are the same.

int x, y;
y = 1;
If y == 1 Then
x = 20;
Else
x = 30;
End If
int x, y;
y = 1;
x == 1 ? 20 : 30;

In Java, these two if-else statements are the same. It is similiar to Ansi C.

int x, y;
y = 1;
if (y == 1) {
x = 20;
} else {
x = 30;
}
int x, y;
y = 1;
x = (y == 1) ? 20: 30;

In C#, these two if-else statements are the same. It is similiar to Java and Ansi C.

int x, y;
y = 1;
if (y == 1) {
x = 20;
} else {
x = 30;
}
<pre><code>int x, y;
y = 1;
x = (y == 1) ? 20: 30;</code></pre>

In VBA, these two if-else statements are the same.

Dim x As Long
Dim y As Long
y = 1
If (y = 1) Then
x = 20
Else
x = 30
End If
<pre><code>Dim x As Long
Dim y As Long
y = 1
x = IIf(y = 1, 20, 30)</code></pre>

Reference