Export (0) Print
Expand All

How to: Break and Combine Statements in Code

When writing your code, you might at times create lengthy statements that necessitate horizontal scrolling in the Code Editor. While this does not affect the way your code runs, it makes it difficult for you or anyone else to read the code as it appears on the monitor. In such cases, you should consider breaking the single long statement into several lines.

At other times, you might want to consolidate statements on a single line, for instance, when you have several very short statements and want to conserve space. This feature can also be handy when organizing variables or commands within a module.

To break a single statement into multiple lines

  • Use the line-continuation character, which is an underscore (_), at the point at which you want the line to break. The underscore must be immediately preceded by a space and immediately followed by a line terminator (carriage return).

    In the following example, the statement is broken into four lines with line-continuation characters terminating all but the last line.

    cmd.CommandText = _
        "SELECT * FROM Titles JOIN Publishers " _
        & "ON Publishers.PubId = Titles.PubID " _
        & "WHERE Publishers.State = 'CA'"
    

    Using this sequence makes your code easier to read, both online and when printed.

    NoteNote:

    The line-continuation character is necessarily the last thing on a line. You cannot follow it with anything else on the same line.

    Some limitations exist as to where the line-continuation character can be used, such as in the middle of an argument name. You can break an argument list with the line-continuation character, but the individual names of the arguments must remain intact.

    NoteNote:

    You cannot continue a comment by using a line-continuation character. Once a comment begins, the compiler does not examine the characters for special meaning. For a multiple-line comment, repeat the comment symbol (') on each line.

While placing each statement on a separate line is the recommended method, Visual Basic also allows you to place multiple statements on the same line.

To place multiple statements on the same line

  • Separate the statements with a colon (:), as in the following example.

    text1.Text = "Hello" : text1.BackColor = System.Drawing.Color.Red
    

Community Additions

ADD
Show:
© 2014 Microsoft