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.

[sourcecode language=”csharp”]
int x, y;
y = 1;
If y == 1 Then
x = 20;
Else
x = 30;
End If
[/sourcecode]

[sourcecode language=”csharp”]
int x, y;
y = 1;
x == 1 ? 20 : 30;
[/sourcecode]

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

[sourcecode language=”csharp”]
int x, y;
y = 1;
if (y == 1) {
x = 20;
} else {
x = 30;
}
[/sourcecode]

[sourcecode language=”csharp”]
int x, y;
y = 1;
x = (y == 1) ? 20: 30;
[/sourcecode]

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

[sourcecode language=”csharp”]
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>
[/sourcecode]

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

[sourcecode language=”csharp”]
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>
[/sourcecode]

Reference