Sideway
output.to from Sideway
Draft for Information Only

Content

VB.NET Statements
 Declaration statements
  Initial Values
 Executable statements
 Assignment statements
  Eligible programming elements
  Data types in assignment statements
  Compound assignment statements
  Type Conversions in Assignment Statements
 Putting multiple statements on one line
 Continuing a statement over multiple lines
  Implicit line continuation
 Adding comments
 Checking compilation errors
 Related sections
  Source/Reference

VB.NET Statements

A statement in Visual Basic is a complete instruction. It can contain keywords, operators, variables, constants, and expressions. Each statement belongs to one of the following categories:

  • Declaration Statements, which name a variable, constant, or procedure, and can also specify a data type.

  • Executable Statements, which initiate actions. These statements can call a method or function, and they can loop or branch through blocks of code. Executable statements include Assignment Statements, which assign a value or expression to a variable or constant.

This topic describes each category. Also, this topic describes how to combine multiple statements on a single line and how to continue a statement over multiple lines.

Declaration statements

You use declaration statements to name and define procedures, variables, properties, arrays, and constants. When you declare a programming element, you can also define its data type, access level, and scope. For more information, see Declared Element Characteristics.

The following example contains three declarations.

VB
Public Sub ApplyFormat()
    Const limit As Integer = 33
    Dim thisWidget As New widget
    ' Insert code to implement the procedure.
End Sub

The first declaration is the Sub statement. Together with its matching End Sub statement, it declares a procedure named applyFormat. It also specifies that applyFormat is Public, which means that any code that can refer to it can call it.

The second declaration is the Const statement, which declares the constant limit, specifying the Integer data type and a value of 33.

The third declaration is the Dim statement, which declares the variable thisWidget. The data type is a specific object, namely an object created from the Widget class. You can declare a variable to be of any elementary data type or of any object type that is exposed in the application you are using.

Initial Values

When the code containing a declaration statement runs, Visual Basic reserves the memory required for the declared element. If the element holds a value, Visual Basic initializes it to the default value for its data type. For more information, see "Behavior" in Dim Statement.

You can assign an initial value to a variable as part of its declaration, as the following example illustrates.

VB
Dim m As Integer = 45
' The preceding declaration creates m and assigns the value 45 to it.

If a variable is an object variable, you can explicitly create an instance of its class when you declare it by using the New Operator keyword, as the following example illustrates.

VB
Dim f As New System.Windows.Forms.Form()

Note that the initial value you specify in a declaration statement is not assigned to a variable until execution reaches its declaration statement. Until that time, the variable contains the default value for its data type.

Executable statements

An executable statement performs an action. It can call a procedure, branch to another place in the code, loop through several statements, or evaluate an expression. An assignment statement is a special case of an executable statement.

The following example uses an If...Then...Else control structure to run different blocks of code based on the value of a variable. Within each block of code, a For...Next loop runs a specified number of times.

VB
Public Sub StartWidget(ByVal aWidget As widget,
    ByVal clockwise As Boolean, ByVal revolutions As Integer)
    Dim counter As Integer
    If clockwise = True Then
        For counter = 1 To revolutions
            aWidget.SpinClockwise()
        Next counter
    Else
        For counter = 1 To revolutions
            aWidget.SpinCounterClockwise()
        Next counter
    End If
End Sub

The If statement in the preceding example checks the value of the parameter clockwise. If the value is True, it calls the spinClockwise method of aWidget. If the value is False, it calls the spinCounterClockwise method of aWidget. The If...Then...Else control structure ends with End If.

The For...Next loop within each block calls the appropriate method a number of times equal to the value of the revolutions parameter.

Assignment statements

Assignment statements carry out assignment operations, which consist of taking the value on the right side of the assignment operator (=) and storing it in the element on the left, as in the following example.

VB
v = 42

In the preceding example, the assignment statement stores the literal value 42 in the variable v.

Eligible programming elements

The programming element on the left side of the assignment operator must be able to accept and store a value. This means it must be a variable or property that is not ReadOnly, or it must be an array element. In the context of an assignment statement, such an element is sometimes called an lvalue, for "left value."

The value on the right side of the assignment operator is generated by an expression, which can consist of any combination of literals, constants, variables, properties, array elements, other expressions, or function calls. The following example illustrates this.

VB
x = y + z + FindResult(3)

The preceding example adds the value held in variable y to the value held in variable z, and then adds the value returned by the call to function findResult. The total value of this expression is then stored in variable x.

Data types in assignment statements

In addition to numeric values, the assignment operator can also assign String values, as the following example illustrates.

VB
Dim a, b As String
a = "String variable assignment"
b = "Con" & "cat" & "enation"
' The preceding statement assigns the value "Concatenation" to b.

You can also assign Boolean values, using either a Boolean literal or a Boolean expression, as the following example illustrates.

VB
Dim r, s, t As Boolean
r = True
s = 45 > 1003
t = 45 > 1003 Or 45 > 17
' The preceding statements assign False to s and True to t.

Similarly, you can assign appropriate values to programming elements of the Char, Date, or Object data type. You can also assign an object instance to an element declared to be of the class from which that instance is created.

Compound assignment statements

Compound assignment statements first perform an operation on an expression before assigning it to a programming element. The following example illustrates one of these operators, +=, which increments the value of the variable on the left side of the operator by the value of the expression on the right.

VB
n += 1

The preceding example adds 1 to the value of n, and then stores that new value in n. It is a shorthand equivalent of the following statement:

VB
n = n + 1

A variety of compound assignment operations can be performed using operators of this type. For a list of these operators and more information about them, see Assignment Operators.

The concatenation assignment operator (&=) is useful for adding a string to the end of already existing strings, as the following example illustrates.

VB
Dim q As String = "Sample "
q &= "String"
' q now contains "Sample String".

Type Conversions in Assignment Statements

The value you assign to a variable, property, or array element must be of a data type appropriate to that destination element. In general, you should try to generate a value of the same data type as that of the destination element. However, some types can be converted to other types during assignment.

For information on converting between data types, see Type Conversions in Visual Basic. In brief, Visual Basic automatically converts a value of a given type to any other type to which it widens. A widening conversion is one in that always succeeds at run time and does not lose any data. For example, Visual Basic converts an Integer value to Double when appropriate, because Integer widens to Double. For more information, see Widening and Narrowing Conversions.

Narrowing conversions (those that are not widening) carry a risk of failure at run time, or of data loss. You can perform a narrowing conversion explicitly by using a type conversion function, or you can direct the compiler to perform all conversions implicitly by setting Option Strict Off. For more information, see Implicit and Explicit Conversions.

Putting multiple statements on one line

You can have multiple statements on a single line separated by the colon (:) character. The following example illustrates this.

VB
Dim sampleString As String = "Hello World" : MsgBox(sampleString)

Though occasionally convenient, this form of syntax makes your code hard to read and maintain. Thus, it is recommended that you keep one statement to a line.

Continuing a statement over multiple lines

A statement usually fits on one line, but when it is too long, you can continue it onto the next line using a line-continuation sequence, which consists of a space followed by an underscore character (_) followed by a carriage return. In the following example, the MsgBox executable statement is continued over two lines.

VB
Public Sub DemoBox()
    Dim nameVar As String
    nameVar = "John"
    MsgBox("Hello " & nameVar _
        & ". How are you?")
End Sub

Implicit line continuation

In many cases, you can continue a statement on the next consecutive line without using the underscore character (_). The following syntax elements implicitly continue the statement on the next line of code.

  • After a comma (,). For example:

    VB
  • Public Function GetUsername(ByVal username As String,
                                ByVal delimiter As Char,
                                ByVal position As Integer) As String
    
        Return username.Split(delimiter)(position)
    End Function
    
  • After an open parenthesis (() or before a closing parenthesis ()). For example:

    VB
  • Dim username = GetUsername(
        Security.Principal.WindowsIdentity.GetCurrent().Name,
        CChar("\"),
        1
      )
    
  • After an open curly brace ({) or before a closing curly brace (}). For example:

    VB
  • Dim customer = New Customer With {
      .Name = "Terry Adams",
      .Company = "Adventure Works",
      .Email = "terry@www.adventure-works.com"
    }
    

    For more information, see Object Initializers: Named and Anonymous Types or Collection Initializers.

  • After an open embedded expression (<%=) or before the close of an embedded expression (%>) within an XML literal. For example:

    VB
  • Dim customerXml = <Customer>
                          <Name>
                              <%=
                                  customer.Name
                              %>
                          </Name>
                          <Email>
                              <%=
                                  customer.Email
                              %>
                          </Email>
                      </Customer>
    

    For more information, see Embedded Expressions in XML.

  • After the concatenation operator (&). For example:

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

    For more information, see Operators Listed by Functionality.

  • After assignment operators (=, &=, :=, +=, -=, *=, /=, \=, ^=, <<=, >>=). For example:

    VB
  • Dim fileStream =
      My.Computer.FileSystem.
        OpenTextFileReader(filePath)
    

    For more information, see Operators Listed by Functionality.

  • After binary operators (+, -, /, *, Mod, <>, <, >, <=, >=, ^, >>, <<, And, AndAlso, Or, OrElse, Like, Xor) within an expression. For example:

    VB
  • Dim memoryInUse =
      My.Computer.Info.TotalPhysicalMemory +
      My.Computer.Info.TotalVirtualMemory -
      My.Computer.Info.AvailablePhysicalMemory -
      My.Computer.Info.AvailableVirtualMemory
    

    For more information, see Operators Listed by Functionality.

  • After the Is and IsNot operators. For example:

    VB
  • If TypeOf inStream Is 
      IO.FileStream AndAlso
      inStream IsNot
      Nothing Then
    
        ReadFile(inStream)
    
    End If
    

    For more information, see Operators Listed by Functionality.

  • After a member qualifier character (.) and before the member name. For example:

    VB
    Dim fileStream =
      My.Computer.FileSystem.
        OpenTextFileReader(filePath)
    

    However, you must include a line-continuation character (_) following a member qualifier character when you are using the With statement or supplying values in the initialization list for a type. Consider breaking the line after the assignment operator (for example, =) when you are using With statements or object initialization lists. For example:

    VB
  • ' Not allowed:
    ' Dim aType = New With { .
    '    PropertyName = "Value"
    
    ' Allowed:
    Dim aType = New With {.PropertyName =
        "Value"}
    
    
    
    Dim log As New EventLog()
    
    ' Not allowed:
    ' With log
    '    .
    '      Source = "Application"
    ' End With
    
    ' Allowed:
    With log
        .Source =
          "Application"
    End With
    

    For more information, see With...End With Statement or Object Initializers: Named and Anonymous Types.

  • After an XML axis property qualifier (. or .@ or ...). However, you must include a line-continuation character (_) when you specify a member qualifier when you are using the With keyword. For example:

    VB
  • Dim customerName = customerXml.
      <Name>.Value
    
    Dim customerEmail = customerXml...
      <Email>.Value
    

    For more information, see XML Axis Properties.

  • After a less-than sign (<) or before a greater-than sign (>) when you specify an attribute. Also after a greater-than sign (>) when you specify an attribute. However, you must include a line-continuation character (_) when you specify assembly-level or module-level attributes. For example:

    VB
  • <
    Serializable()
    >
    Public Class Customer
        Public Property Name As String
        Public Property Company As String
        Public Property Email As String
    End Class
    

    For more information, see Attributes overview.

  • Before and after query operators (Aggregate, Distinct, From, Group By, Group Join, Join, Let, Order By, Select, Skip, Skip While, Take, Take While, Where, In, Into, On, Ascending, and Descending). You cannot break a line between the keywords of query operators that are made up of multiple keywords (Order By, Group Join, Take While, and Skip While). For example:

    VB
  • Dim vsProcesses = From proc In
                        Process.GetProcesses
                      Where proc.MainWindowTitle.Contains("Visual Studio")
                      Select proc.ProcessName, proc.Id,
                             proc.MainWindowTitle
    

    For more information, see Queries.

  • After the In keyword in a For Each statement. For example:

    VB
  • For Each p In
      vsProcesses
    
        Console.WriteLine("{0}" & vbTab & "{1}" & vbTab & "{2}",
          p.ProcessName,
          p.Id,
          p.MainWindowTitle)
    Next
    

    For more information, see For Each...Next Statement.

  • After the From keyword in a collection initializer. For example:

    VB
    • Dim days = New List(Of String) From
        {
         "Mo", "Tu", "We", "Th", "F", "Sa", "Su"
        }
      

      For more information, see Collection Initializers.

    Adding comments

    Source code is not always self-explanatory, even to the programmer who wrote it. To help document their code, therefore, most programmers make liberal use of embedded comments. Comments in code can explain a procedure or a particular instruction to anyone reading or working with it later. Visual Basic ignores comments during compilation, and they do not affect the compiled code.

    Comment lines begin with an apostrophe (') or REM followed by a space. They can be added anywhere in code, except within a string. To append a comment to a statement, insert an apostrophe or REM after the statement, followed by the comment. Comments can also go on their own separate line. The following example demonstrates these possibilities.

    VB
    ' This is a comment on a separate code line.
    REM This is another comment on a separate code line.
    x += a(i) * b(i) ' Add this amount to total.
    MsgBox(statusMessage) REM Inform operator of status.
    

    Checking compilation errors

    If, after you type a line of code, the line is displayed with a wavy blue underline (an error message may appear as well), there is a syntax error in the statement. You must find out what is wrong with the statement (by looking in the task list, or hovering over the error with the mouse pointer and reading the error message) and correct it. Until you have fixed all syntax errors in your code, your program will fail to compile correctly.

    Related sections

    Term Definition
    Assignment Operators Provides links to language reference pages covering assignment operators such as =, *=, and &=.
    Operators and Expressions Shows how to combine elements with operators to yield new values.
    How to: Break and Combine Statements in Code Shows how to break a single statement into multiple lines and how to place multiple statements on the same line.
    How to: Label Statements Shows how to label a line of code.
  •  

    Source/Reference


    ©sideway

    ID: 201000009 Last Updated: 10/9/2020 Revision: 0 Ref:

    close

    References

    1. Active Server Pages,  , http://msdn.microsoft.com/en-us/library/aa286483.aspx
    2. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929%28v=vs.90%29.aspx
    3. ASP Best Practices,  , http://technet.microsoft.com/en-us/library/cc939157.aspx
    4. ASP Built-in Objects,  , http://msdn.microsoft.com/en-us/library/ie/ms524716(v=vs.90).aspx
    5. Response Object,  , http://msdn.microsoft.com/en-us/library/ms525405(v=vs.90).aspx
    6. Request Object,  , http://msdn.microsoft.com/en-us/library/ms524948(v=vs.90).aspx
    7. Server Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525541(v=vs.90).aspx
    8. Application Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525360(v=vs.90).aspx
    9. Session Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms524319(8v=vs.90).aspx
    10. ASPError Object,  , http://msdn.microsoft.com/en-us/library/ms524942(v=vs.90).aspx
    11. ObjectContext Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525667(v=vs.90).aspx
    12. Debugging Global.asa Files,  , http://msdn.microsoft.com/en-us/library/aa291249(v=vs.71).aspx
    13. How to: Debug Global.asa files,  , http://msdn.microsoft.com/en-us/library/ms241868(v=vs.80).aspx
    14. Calling COM Components from ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524620(v=VS.90).aspx
    15. IIS ASP Scripting Reference,  , http://msdn.microsoft.com/en-us/library/ms524664(v=vs.90).aspx
    16. ASP Keywords,  , http://msdn.microsoft.com/en-us/library/ms524672(v=vs.90).aspx
    17. Creating Simple ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524741(v=vs.90).aspx
    18. Including Files in ASP Applications,  , http://msdn.microsoft.com/en-us/library/ms524876(v=vs.90).aspx
    19. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929(v=vs.90).aspx
    20. FileSystemObject Object,  , http://msdn.microsoft.com/en-us/library/z9ty6h50(v=vs.84).aspx
    21. http://msdn.microsoft.com/en-us/library/windows/desktop/ms675944(v=vs.85).aspx,  , ADO Object Model
    22. ADO Fundamentals,  , http://msdn.microsoft.com/en-us/library/windows/desktop/ms680928(v=vs.85).aspx
    close

    Latest Updated LinksValid XHTML 1.0 Transitional Valid CSS!Nu Html Checker Firefox53 Chromena IExplorerna
    IMAGE

    Home 5

    Business

    Management

    HBR 3

    Information

    Recreation

    Hobbies 8

    Culture

    Chinese 1097

    English 339

    Reference 79

    Computer

    Hardware 249

    Software

    Application 213

    Digitization 32

    Latex 52

    Manim 205

    KB 1

    Numeric 19

    Programming

    Web 289

    Unicode 504

    HTML 66

    CSS 65

    SVG 46

    ASP.NET 270

    OS 429

    DeskTop 7

    Python 72

    Knowledge

    Mathematics

    Formulas 8

    Algebra 84

    Number Theory 206

    Trigonometry 31

    Geometry 34

    Coordinate Geometry 2

    Calculus 67

    Complex Analysis 21

    Engineering

    Tables 8

    Mechanical

    Mechanics 1

    Rigid Bodies

    Statics 92

    Dynamics 37

    Fluid 5

    Fluid Kinematics 5

    Control

    Process Control 1

    Acoustics 19

    FiniteElement 2

    Natural Sciences

    Matter 1

    Electric 27

    Biology 1

    Geography 1


    Copyright © 2000-2024 Sideway . All rights reserved Disclaimers last modified on 06 September 2019