If...Then...Else 문(Visual Basic)

식의 값에 따라 문 그룹을 조건부로 실행합니다.

구문

' Multiline syntax:
If condition [ Then ]
    [ statements ]
[ ElseIf elseifcondition [ Then ]
    [ elseifstatements ] ]
[ Else
    [ elsestatements ] ]
End If

' Single-line syntax:
If condition Then [ statements ] [ Else [ elsestatements ] ]

이 문서에는 If...Then...Else 문의 사용을 보여 주는 몇 가지 예제가 포함되어 있습니다.

부분

condition
필수입니다. 식 True 또는 False, 또는 암시적으로 Boolean(으)로 변환할 수 있는 데이터 형식으로 평가해야 합니다.

식이 Nothing으로 계산되는 NullableBoolean 변수인 경우 조건은 식이 False인것처럼 처리되고 ElseIf 블록이 있는 경우 평가되거나 Else 블록이 있는 경우 실행됩니다.

Then
한 줄 구문에 필요합니다. 다중 줄 구문의 선택 사항입니다.

statements
선택 사항. condition(이)가 True(으)로 평가되면 실행되는 If...Then에 따라오는 하나 이상의 문입니다.

elseifcondition
ElseIf(이)가 있는 경우 필요합니다. 식 True 또는 False, 또는 암시적으로 Boolean(으)로 변환할 수 있는 데이터 형식으로 평가해야 합니다.

elseifstatements
선택 사항. ElseIf(이)가 Then(으)로 평가되면 실행되는 ElseIf...Then에 따라오는 하나 이상의 문입니다.

elsestatements
선택 사항. 이전 condition 또는 elseifcondition 식이 True평가되지 않는 경우 실행되는 하나 이상의 문입니다.

End If
If...Then...Else 블록의 여러 줄 버전을 종료합니다.

설명

여러 줄 구문

If...Then...Else 문이 발견되면 condition(이)가 테스트됩니다. condition(이)가 True인 경우 Then 다음 문이 실행됩니다. condition(이)가 False인 경우 각 ElseIf 문(있는 경우)이 순서대로 평가됩니다. Trueelseifcondition(이)가 발견되면 연결된 바로 다음에 있는 문 ElseIf(이)가 실행됩니다. elseifcondition(이)가 True로 평가되지 않거나 혹은 만약 ElseIf문이 없으면 Else 다음 문이 실행됩니다. Then, ElseIf 또는 Else다음 문을 실행한 후 End If 다음 문을 계속 실행합니다.

ElseIf (와)과 Else 절은 모두 선택 사항입니다. If...Then...Else문에서 원하는 만큼 ElseIf 절을 가질 수 있지만 Else 절 후에는 ElseIf 절이 나타날 수 없습니다. If...Then...Else 문은 서로 중첩 될 수 있습니다.

여러 줄 구문에서 If 문은 첫 번째 줄에서 유일한 문이어야 합니다. ElseIf, ElseEnd If 문 앞에 줄 레이블만 지정할 수 있습니다. If...Then...Else 블록은 End If 문으로 끝나야합니다.

Select... Case Statement는 몇 가지 가능한 값이 있는 단일 식을 평가할 때 더 유용할 수 있습니다.

한 줄 구문

단일 조건에 대한 단일 줄 구문을 코드와 함께 사용하여 true인 경우 실행할 수 있습니다. 그러나 여러 줄 구문은 더 많은 구조와 유연성을 제공하며 읽기, 유지 관리 및 디버그가 더 쉽습니다.

Then 키워드 다음에는 문이 한 줄 If인지 여부를 확인하기 위해 검사됩니다. 주석이 아닌 다른 항목이 동일한 줄에 Then 후 나타나는 경우 문은 한 줄 If 문으로 처리됩니다. Then(이)가 없는 경우 여러 줄 IfThen...Else(으)로 시작해야 합니다.

한 줄 구문에서는 If...Then 결정의 결과로 여러 문을 실행할 수 있습니다. 모든 문은 동일한 줄에 있어야 하며 콜론으로 구분되어야 합니다.

여러 줄 구문 예제

다음 예제에서는 If...Then...Else 문의 여러 줄 구문을 사용하는 방법을 보여 줍니다.

'Create a Random object to seed our starting value 
Dim randomizer As New Random()
'set our variable
Dim count As Integer = randomizer.Next(0, 5)

Dim message As String

'If count is zero, output will be no items
If count = 0 Then
    message = "There are no items."
    'If count is 1, output will be "There is 1 item.".        
ElseIf count = 1 Then
    message = "There is 1 item."
    'If count is greater than 1, output will be "There are {count} items.", where {count} is replaced by the value of count. 
Else
    message = $"There are {count} items."
End If

Console.WriteLine(message)

'This example displays output like the following:
' There are 4 items.

중첩 구문 예제

다음 예제에는 중첩된 If...Then...Else 문이 포함되어 있습니다.

Public Sub Main()
    ' Run the function as part of the WriteLine output.
    Console.WriteLine("Time Check is " & CheckIfTime() & ".")
End Sub

Private Function CheckIfTime() As Boolean
    ' Determine the current day of week and hour of day.
    Dim dayW As DayOfWeek = DateTime.Now.DayOfWeek
    Dim hour As Integer = DateTime.Now.Hour

    ' Return True if Wednesday from 2 to 3:59 P.M.,
    ' or if Thursday from noon to 12:59 P.M.
    If dayW = DayOfWeek.Wednesday Then
        If hour = 14 Or hour = 15 Then
            Return True
        Else
            Return False
        End If
    ElseIf dayW = DayOfWeek.Thursday Then
        If hour = 12 Then
            Return True
        Else
            Return False
        End If
    Else
        Return False
    End If
End Function

'This example displays output like the following:
'Time Check is False.

한 줄 구문 예제

다음 예제에서는 한 줄 구문을 사용하는 방법을 보여 줍니다.

Private Sub SingleLine()

    'Create a Random object to seed our starting values 
    Dim randomizer As New Random()

    Dim A As Integer = randomizer.Next(10, 20)
    Dim B As Integer = randomizer.Next(0, 20)
    Dim C As Integer = randomizer.Next(0, 5)

    'Let's display the initial values for comparison
    Console.WriteLine($"A value before If: {A}")
    Console.WriteLine($"B value before If: {B}")
    Console.WriteLine($"C value before If: {C}")

    ' If A > 10, execute the three colon-separated statements in the order
    ' that they appear
    If A > 10 Then A = A + 1 : B = B + A : C = C + B

    'If the condition is true, the values will be different
    Console.WriteLine($"A value after If: {A}")
    Console.WriteLine($"B value after If: {B}")
    Console.WriteLine($"C value after If: {C}")

End Sub

'This example displays output like the following:
'A value before If: 11
'B value before If: 6
'C value before If: 3
'A value after If: 12
'B value after If: 18
'C value after If: 21

참고 항목