Is "Then" really necessary at the end of the If block?

Asked

Viewed 162 times

12

The Visual Basic . NET compiler seems to ignore the reserved word Then, the one at the end of the block If.

 If (1 + 1 = 2) Then
      Console.WriteLine("Passou no teste.")
 End If

And now, without the Then:

 If (1 + 1 = 2)
      Console.WriteLine("Também passou no teste.")
 End If

This was the result in the Console:

Passou no teste.

Também passou no teste.

A Keyword Then is it really necessary in Visual Basic . NET? It has a special function or is it some kind of "Improve code reading"?

1 answer

13


It is only required when it will use commands on a line, so it is the separator. When it will execute a block of commands it is optional even.

Documentation.

Example of single line:

If x > 0 Then y = 0

Or more than one command on a line:

If x > 0 Then y = 0 : z = 0

Code block:

If x > 0
    y = 0
    z = 0
End If

Also works the same:

If x > 0 Then
    y = 0
    z = 0
End If

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.