Share via


How to: Break and Combine Statements in Code (Visual Basic)

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 or a line terminator (carriage return). In some cases, you can omit the line-continuation character and the Visual Basic compiler will implicitly continue the statement on the next line of code. For a list of syntax elements for which the line-continuation character can be omitted, see "Implicit Line Continuation" in Statements in Visual Basic.

    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.

    Note

    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.

    Note

    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
    

See Also

Other Resources

Program Structure and Code Conventions (Visual Basic)

Statements in Visual Basic