# If 運算子 (Visual Basic)

## 語法

If( [argument1,] argument2, argument3 )


## 使用三個引數呼叫 if 運算子

### 組件

argument1 必要。 Boolean. 決定要評估並傳回的其他引數的哪一個。
argument2 必要。 Object. 若 argument1 評估為 True，則予以評估並傳回。
argument3 必要。 Object. 若 argument1 評估為 False，則予以評估並傳回；若 argument1可為 Null 的 Boolean 變數，則評估為 Nothing

' This statement prints TruePart, because the first argument is true.
Console.WriteLine(If(True, "TruePart", "FalsePart"))

' This statement prints FalsePart, because the first argument is false.
Console.WriteLine(If(False, "TruePart", "FalsePart"))

Dim number = 3
' With number set to 3, this statement prints Positive.
Console.WriteLine(If(number >= 0, "Positive", "Negative"))

number = -1
' With number set to -1, this statement prints Negative.
Console.WriteLine(If(number >= 0, "Positive", "Negative"))


number = 12

' When the divisor is not 0, both If and IIf return 4.
Dim divisor = 3
Console.WriteLine(If(divisor <> 0, number \ divisor, 0))
Console.WriteLine(IIf(divisor <> 0, number \ divisor, 0))

' When the divisor is 0, IIf causes a run-time error, but If does not.
divisor = 0
Console.WriteLine(If(divisor <> 0, number \ divisor, 0))
' Console.WriteLine(IIf(divisor <> 0, number \ divisor, 0))


## 使用兩個引數呼叫 if 運算子

If 的第一個引數可以省略。 這樣即可只使用兩個引數呼叫運算子。 只有在使用兩個引數呼叫 If 運算子時，才適用下列清單。

### 組件

argument2 必要。 Object. 必須是參考或可為 Null 的實值型別。 評估為 Nothing 以外的任何值時，則予以評估並傳回。
argument3 必要。 Object. 若 argument2 評估為 Nothing，則予以評估並傳回。

' 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))