Search code examples
c#vb.netif-statementlanguage-comparisons

Are THEN and END IF the exact equivalent of curly brackets


Does the compiler see the same thing when it sees THEN...END IF(in Vb) and { ... }(in C#) which are what seems to be delimiting If statements.

If they are treated the same way, why can I do this in C# :

if(true)
 int x = 1;

//Instead of

if(true)
{ 
 int x = 1;
}

But not in VB :

//Won't Compile

if(true)
x As Integer = 1

//Instead Of

if(true) then
x As Integer = 1
End If

Solution

  • C# and vb.net have different rules when it comes to parsing statements. VB.net is derived from QuickBasic, which was derived from Microsoft BASIC interpreters in which an IF/THEN statement with a false condition would cause the interpreter to skip ahead until the end of the line or an ELSE statement, whichever occurred first. Because it was somewhat annoying having to place all the statements conditioned on an IF statement on the same line as that statement, QuickBasic was designed so that if a line contains an IF/THEN, ELSEIF/THEN, or an ELSE but no other statements, execution will skip until the next corresponding ELSEIF, ELSE, or ENDIF.

    While the VB syntax is somewhat ad hoc, it actually works out quite nicely. One thing that might be nice in both languages would be a statement whose clearly-defined purpose was to begin a variable-scoping block. In vb.net, one can say:

    If True Then ' Scoping block
      Dim SB As New System.Text.StringBuilder()
      ...
    End If
    

    but that seems a bit icky. The ability to use braces alone for that purpose in C# might be seen as a "win" for that language, but absent a comment it's wouldn't be clear when reading code that the purpose of the braces was to serve as a variable-scoping block, rather than grouping some statements that were supposed to be executed conditionally or repeatedly, but for whatever reason "lost" their control statement.