Declaration Statements in Visual Basic

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.

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 (Visual Basic).

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

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 (Visual Basic) keyword, as the following example illustrates.

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.

See Also


How to: Declare A Constant


Statements Overview

Assignment Statements

Executable Statements