The accepted answer doesn't have any explanation whatsoever and is simply just a link.
Therefore, I thought I'd leave an answer that explains how the
If operator works taken from MSDN:
Uses short-circuit evaluation to conditionally return one of two values. The If operator can be called with three arguments or with two arguments.
If( [argument1,] argument2, argument3 )
If Operator Called with Two Arguments
The first argument to If can be omitted. This enables the operator to be called by using only two arguments. The following list applies only when the If operator is called with two arguments.
Term Definition ---- ---------- argument2 Required. Object. Must be a reference or nullable type. Evaluated and returned when it evaluates to anything other than Nothing. argument3 Required. Object. Evaluated and returned if argument2 evaluates to Nothing.
When the Boolean argument is omitted, the first argument must be a reference or nullable type. If the first argument evaluates to Nothing, the value of the second argument is returned. In all other cases, the value of the first argument is returned. The following example illustrates how this evaluation works.
' Variable first is a nullable type. Dim first? As Integer = 3 Dim second As Integer = 6 ' Variable first <> Nothing, so its value, 3, is returned. Console.WriteLine(If(first, second)) second = Nothing ' Variable first <> Nothing, so the value of first is returned again. Console.WriteLine(If(first, second)) first = Nothing second = 6 ' Variable first = Nothing, so 6 is returned. Console.WriteLine(If(first, second))
An example of how to handle more than two values (nested
Dim first? As Integer = Nothing Dim second? As Integer = Nothing Dim third? As Integer = 6 ' The LAST parameter doesn't have to be nullable. 'Alternative: Dim third As Integer = 6 ' Writes "6", because the first two values are "Nothing". Console.WriteLine(If(first, If(second, third)))