Sideway
output.to from Sideway
Draft for Information Only

Content

VB.NET Declaration Statements
  Const Statement
  Syntax
  Parts
  Remarks
  Rules
  Data Type Rules
  Behavior
  See also
  Delegate Statement
  Syntax
  Parts
  Remarks
  See also
  Dim Statement
  Syntax
  Parts
  Remarks
  Specifying an Initial Value
  Declaring Multiple Variables
  Arrays
  Default Data Types and Values
  Static Local Variable Lifetime
  Attributes and Modifiers
  Releasing Managed Resources
  See also
  Event Statement
  Syntax
  Parts
  Remarks
  See also
  Implements Statement
  Syntax
  Parts
  Remarks
  See also
  Imports Statement (.NET Namespace and Type)
  Syntax
  Parts
  Remarks
  Import Aliases
  Element Names
  See also
  Imports Statement (XML Namespace)
  Syntax
  Parts
  Remarks
  See also
  Inherits Statement
  Syntax
  Parts
  Remarks
  Rules
  See also
  Interface Statement
  Syntax
  Parts
  Remarks
  Rules
  Behavior
  See also
  Namespace Statement
  Syntax
  Parts
  Remarks
  Access Level
  Root Namespace
  Attributes and Modifiers
  See also
  ReDim Statement
  Syntax
  Parts
  Remarks
  Rules
  Behavior
  See also
 Source/Reference

VB.NET Declaration Statements

The supporting VB.NET Declaration Statements are Const, Delegate, Dim, Implements, Imports (.NET Namespace and Type), Imports (XML Namespace), Inherits, Interface, Namespace, ReDim,                 Event, Private, Public

Const Statement

Declares and defines one or more constants.

Syntax

[ <attributelist> ] [ accessmodifier ] [ Shadows ]   
Const constantlist  

Parts

attributelist
Optional. List of attributes that apply to all the constants declared in this statement. See Attribute List in angle brackets ("<" and ">").

accessmodifier
Optional. Use this to specify what code can access these constants. Can be Public, Protected, Friend, Protected Friend, Private, or Private Protected.

Shadows
Optional. Use this to redeclare and hide a programming element in a base class. See Shadows.

constantlist
Required. List of constants being declared in this statement.

constant [ , constant ... ]

Each constant has the following syntax and parts:

constantname [ As datatype ] = initializer

Part Description
constantname Required. Name of the constant. See Declared Element Names.
datatype Required if Option Strict is On. Data type of the constant.
initializer Required. Expression that is evaluated at compile time and assigned to the constant.

Remarks

If you have a value that never changes in your application, you can define a named constant and use it in place of a literal value. A name is easier to remember than a value. You can define the constant just once and use it in many places in your code. If in a later version you need to redefine the value, the Const statement is the only place you need to make a change.

You can use Const only at module or procedure level. This means the declaration context for a variable must be a class, structure, module, procedure, or block, and cannot be a source file, namespace, or interface. For more information, see Declaration Contexts and Default Access Levels.

Local constants (inside a procedure) default to public access, and you cannot use any access modifiers on them. Class and module member constants (outside any procedure) default to private access, and structure member constants default to public access. You can adjust their access levels with the access modifiers.

Rules

  • Declaration Context. A constant declared at module level, outside any procedure, is a member constant; it is a member of the class, structure, or module that declares it.

    A constant declared at procedure level is a local constant; it is local to the procedure or block that declares it.

  • Attributes. You can apply attributes only to member constants, not to local constants. An attribute contributes information to the assembly's metadata, which is not meaningful for temporary storage such as local constants.

  • Modifiers. By default, all constants are Shared, Static, and ReadOnly. You cannot use any of these keywords when declaring a constant.

    At procedure level, you cannot use Shadows or any access modifiers to declare local constants.

  • Multiple Constants. You can declare several constants in the same declaration statement, specifying the constantname part for each one. Multiple constants are separated by commas.

Data Type Rules

  • Data Types. The Const statement can declare the data type of a variable. You can specify any data type or the name of an enumeration.

  • Default Type. If you do not specify datatype, the constant takes the data type of initializer. If you specify both datatype and initializer, the data type of initializer must be convertible to datatype. If neither datatype nor initializer is present, the data type defaults to Object.

  • Different Types. You can specify different data types for different constants by using a separate As clause for each variable you declare. However, you cannot declare several constants to be of the same type by using a common As clause.

  • Initialization. You must initialize the value of every constant in constantlist. You use initializer to supply an expression to be assigned to the constant. The expression can be any combination of literals, other constants that are already defined, and enumeration members that are already defined. You can use arithmetic and logical operators to combine such elements.

    You cannot use variables or functions in initializer. However, you can use conversion keywords such as CByte and CShort. You can also use AscW if you call it with a constant String or Char argument, since that can be evaluated at compile time.

Behavior

  • Scope. Local constants are accessible only from within their procedure or block. Member constants are accessible from anywhere within their class, structure, or module.

  • Qualification. Code outside a class, structure, or module must qualify a member constant's name with the name of that class, structure, or module. Code outside a procedure or block cannot refer to any local constants within that procedure or block.

See also

Delegate Statement

Used to declare a delegate. A delegate is a reference type that refers to a Shared method of a type or to an instance method of an object. Any procedure with matching parameter and return types can be used to create an instance of this delegate class. The procedure can then later be invoked by means of the delegate instance.

Syntax

[ <attrlist> ] [ accessmodifier ] _  
[ Shadows ] Delegate [ Sub | Function ] name [( Of typeparamlist )] [([ parameterlist ])] [ As type ]  

Parts

Term Definition
attrlist Optional. List of attributes that apply to this delegate. Multiple attributes are separated by commas. You must enclose the Attribute List in angle brackets ("<" and ">").
accessmodifier Optional. Specifies what code can access the delegate. Can be one of the following:

- Public. Any code that can access the element that declares the delegate can access it.
- Protected. Only code within the delegate's class or a derived class can access it.
- Friend. Only code within the same assembly can access the delegate.
- Private. Only code within the element that declares the delegate can access it.

- Protected Friend Only code within the delegate's class, a derived class, or the same assembly can access the delegate.
- Private Protected Only code within the delegate's class or in a derived class in the same assembly can access the delegate.
Shadows Optional. Indicates that this delegate redeclares and hides an identically named programming element, or set of overloaded elements, in a base class. You can shadow any kind of declared element with any other kind.

A shadowed element is unavailable from within the derived class that shadows it, except from where the shadowing element is inaccessible. For example, if a Private element shadows a base class element, code that does not have permission to access the Private element accesses the base class element instead.
Sub Optional, but either Sub or Function must appear. Declares this procedure as a delegate Sub procedure that does not return a value.
Function Optional, but either Sub or Function must appear. Declares this procedure as a delegate Function procedure that returns a value.
name Required. Name of the delegate type; follows standard variable naming conventions.
typeparamlist Optional. List of type parameters for this delegate. Multiple type parameters are separated by commas. Optionally, each type parameter can be declared variant by using In and Out generic modifiers. You must enclose the Type List in parentheses and introduce it with the Of keyword.
parameterlist Optional. List of parameters that are passed to the procedure when it is called. You must enclose the Parameter List in parentheses.
type Required if you specify a Function procedure. Data type of the return value.

Remarks

The Delegate statement defines the parameter and return types of a delegate class. Any procedure with matching parameters and return types can be used to create an instance of this delegate class. The procedure can then later be invoked by means of the delegate instance, by calling the delegate's Invoke method.

Delegates can be declared at the namespace, module, class, or structure level, but not within a procedure.

Each delegate class defines a constructor that is passed the specification of an object method. An argument to a delegate constructor must be a reference to a method, or a lambda expression.

To specify a reference to a method, use the following syntax:

AddressOf [expression.]methodname

The compile-time type of the expression must be the name of a class or an interface that contains a method of the specified name whose signature matches the signature of the delegate class. The methodname can be either a shared method or an instance method. The methodname is not optional, even if you create a delegate for the default method of the class.

To specify a lambda expression, use the following syntax:

Function ([parm As type, parm2 As type2, ...]) expression

The signature of the function must match that of the delegate type. For more information about lambda expressions, see Lambda Expressions.

For more information about delegates, see Delegates.

See also

Dim Statement

Declares and allocates storage space for one or more variables.

Syntax

[ <attributelist> ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]] [ ReadOnly ]
Dim [ WithEvents ] variablelist

Parts

Optional. Specifies that these are object variables that refer to instances of a class that can raise events. See WithEvents.

  • variablelist

    Required. List of variables being declared in this statement.

    variable [ , variable ... ]

    Each variable has the following syntax and parts:

    variablename [ ( [ boundslist ] ) ] [ As [ New ] datatype [ With{[ .propertyname = propinitializer [ , ... ] ] } ] ] [ = initializer ]

    Part Description
    variablename Required. Name of the variable. See Declared Element Names.
    boundslist Optional. List of bounds of each dimension of an array variable.
    New Optional. Creates a new instance of the class when the Dim statement runs.
    datatype Optional. Data type of the variable.
    With Optional. Introduces the object initializer list.
    propertyname Optional. The name of a property in the class you are making an instance of.
    propinitializer Required after propertyname =. The expression that is evaluated and assigned to the property name.
    initializer Optional if New is not specified. Expression that is evaluated and assigned to the variable when it is created.

Remarks

The Visual Basic compiler uses the Dim statement to determine the variable's data type and other information, such as what code can access the variable. The following example declares a variable to hold an Integer value.

VB
Dim numberOfStudents As Integer

You can specify any data type or the name of an enumeration, structure, class, or interface.

VB
Dim finished As Boolean
Dim monitorBox As System.Windows.Forms.Form

For a reference type, you use the New keyword to create a new instance of the class or structure that is specified by the data type. If you use New, you do not use an initializer expression. Instead, you supply arguments, if they are required, to the constructor of the class from which you are creating the variable.

VB
Dim bottomLabel As New System.Windows.Forms.Label

You can declare a variable in a procedure, block, class, structure, or module. You cannot declare a variable in a source file, namespace, or interface. For more information, see Declaration Contexts and Default Access Levels.

A variable that is declared at module level, outside any procedure, is a member variable or field. Member variables are in scope throughout their class, structure, or module. A variable that is declared at procedure level is a local variable. Local variables are in scope only within their procedure or block.

The following access modifiers are used to declare variables outside a procedure: Public, Protected, Friend, Protected Friend, and Private. For more information, see Access levels in Visual Basic.

The Dim keyword is optional and usually omitted if you specify any of the following modifiers: Public, Protected, Friend, Protected Friend, Private, Shared, Shadows, Static, ReadOnly, or WithEvents.

VB
Public maximumAllowed As Double
Protected Friend currentUserName As String
Private salary As Decimal
Static runningTotal As Integer

If Option Explicit is on (the default), the compiler requires a declaration for every variable you use. For more information, see Option Explicit Statement.

Specifying an Initial Value

You can assign a value to a variable when it is created. For a value type, you use an initializer to supply an expression to be assigned to the variable. The expression must evaluate to a constant that can be calculated at compile time.

VB
Dim quantity As Integer = 10
Dim message As String = "Just started"

If an initializer is specified and a data type is not specified in an As clause, type inference is used to infer the data type from the initializer. In the following example, both num1 and num2 are strongly typed as integers. In the second declaration, type inference infers the type from the value 3.

VB
' Use explicit typing.
Dim num1 As Integer = 3

' Use local type inference.
Dim num2 = 3

Type inference applies at the procedure level. It does not apply outside a procedure in a class, structure, module, or interface. For more information about type inference, see Option Infer Statement and Local Type Inference.

For information about what happens when a data type or initializer is not specified, see Default Data Types and Values later in this topic.

You can use an object initializer to declare instances of named and anonymous types. The following code creates an instance of a Student class and uses an object initializer to initialize properties.

VB
Dim student1 As New Student With {.First = "Michael",
                                  .Last = "Tucker"}

For more information about object initializers, see How to: Declare an Object by Using an Object Initializer, Object Initializers: Named and Anonymous Types, and Anonymous Types.

Declaring Multiple Variables

You can declare several variables in one declaration statement, specifying the variable name for each one, and following each array name with parentheses. Multiple variables are separated by commas.

VB
Dim lastTime, nextTime, allTimes() As Date

If you declare more than one variable with one As clause, you cannot supply an initializer for that group of variables.

You can specify different data types for different variables by using a separate As clause for each variable you declare. Each variable takes the data type specified in the first As clause encountered after its variablename part.

VB
Dim a, b, c As Single, x, y As Double, i As Integer
' a, b, and c are all Single; x and y are both Double

Arrays

You can declare a variable to hold an array, which can hold multiple values. To specify that a variable holds an array, follow its variablename immediately with parentheses. For more information about arrays, see Arrays.

You can specify the lower and upper bound of each dimension of an array. To do this, include a boundslist inside the parentheses. For each dimension, the boundslist specifies the upper bound and optionally the lower bound. The lower bound is always zero, whether you specify it or not. Each index can vary from zero through its upper bound value.

The following two statements are equivalent. Each statement declares an array of 21 Integer elements. When you access the array, the index can vary from 0 through 20.

VB
Dim totals(20) As Integer
Dim totals(0 To 20) As Integer

The following statement declares a two-dimensional array of type Double. The array has 4 rows (3 + 1) of 6 columns (5 + 1) each. Note that an upper bound represents the highest possible value for the index, not the length of the dimension. The length of the dimension is the upper bound plus one.

VB
Dim matrix2(3, 5) As Double

An array can have from 1 to 32 dimensions.

You can leave all the bounds blank in an array declaration. If you do this, the array has the number of dimensions you specify, but it is uninitialized. It has a value of Nothing until you initialize at least some of its elements. The Dim statement must specify bounds either for all dimensions or for no dimensions.

VB
' Declare an array with blank array bounds.
Dim messages() As String
' Initialize the array.
ReDim messages(4)

If the array has more than one dimension, you must include commas between the parentheses to indicate the number of dimensions.

VB
Dim oneDimension(), twoDimensions(,), threeDimensions(,,) As Byte

You can declare a zero-length array by declaring one of the array's dimensions to be -1. A variable that holds a zero-length array does not have the value Nothing. Zero-length arrays are required by certain common language runtime functions. If you try to access such an array, a runtime exception occurs. For more information, see Arrays.

You can initialize the values of an array by using an array literal. To do this, surround the initialization values with braces ({}).

VB
Dim longArray() As Long = {0, 1, 2, 3}

For multidimensional arrays, the initialization for each separate dimension is enclosed in braces in the outer dimension. The elements are specified in row-major order.

VB
Dim twoDimensions(,) As Integer = {{0, 1, 2}, {10, 11, 12}}

For more information about array literals, see Arrays.

Default Data Types and Values

The following table describes the results of various combinations of specifying the data type and initializer in a Dim statement.

Data type specified? Initializer specified? Example Result
No No Dim qty If Option Strict is off (the default), the variable is set to Nothing.

If Option Strict is on, a compile-time error occurs.
No Yes Dim qty = 5 If Option Infer is on (the default), the variable takes the data type of the initializer. See Local Type Inference.

If Option Infer is off and Option Strict is off, the variable takes the data type of Object.

If Option Infer is off and Option Strict is on, a compile-time error occurs.
Yes No Dim qty As Integer The variable is initialized to the default value for the data type. See the table later in this section.
Yes Yes Dim qty As Integer = 5 If the data type of the initializer is not convertible to the specified data type, a compile-time error occurs.

If you specify a data type but do not specify an initializer, Visual Basic initializes the variable to the default value for its data type. The following table shows the default initialization values.

Data type Default value
All numeric types (including Byte and SByte) 0
Char Binary 0
All reference types (including Object, String, and all arrays) Nothing
Boolean False
Date 12:00 AM of January 1 of the year 1 (01/01/0001 12:00:00 AM)

Each element of a structure is initialized as if it were a separate variable. If you declare the length of an array but do not initialize its elements, each element is initialized as if it were a separate variable.

Static Local Variable Lifetime

A Static local variable has a longer lifetime than that of the procedure in which it is declared. The boundaries of the variable's lifetime depend on where the procedure is declared and whether it is Shared.

Procedure declaration Variable initialized Variable stops existing
In a module The first time the procedure is called When your program stops execution
In a class or structure, procedure is Shared The first time the procedure is called either on a specific instance or on the class or structure itself When your program stops execution
In a class or structure, procedure isn't Shared The first time the procedure is called on a specific instance When the instance is released for garbage collection (GC)

Attributes and Modifiers

You can apply attributes only to member variables, not to local variables. An attribute contributes information to the assembly's metadata, which is not meaningful for temporary storage such as local variables.

At module level, you cannot use the Static modifier to declare member variables. At procedure level, you cannot use Shared, Shadows, ReadOnly, WithEvents, or any access modifiers to declare local variables.

You can specify what code can access a variable by supplying an accessmodifier. Class and module member variables (outside any procedure) default to private access, and structure member variables default to public access. You can adjust their access levels with the access modifiers. You cannot use access modifiers on local variables (inside a procedure).

You can specify WithEvents only on member variables, not on local variables inside a procedure. If you specify WithEvents, the data type of the variable must be a specific class type, not Object. You cannot declare an array with WithEvents. For more information about events, see Events.

Note

Code outside a class, structure, or module must qualify a member variable's name with the name of that class, structure, or module. Code outside a procedure or block cannot refer to any local variables within that procedure or block.

Releasing Managed Resources

The .NET Framework garbage collector disposes of managed resources without any extra coding on your part. However, you can force the disposal of a managed resource instead of waiting for the garbage collector.

If a class holds onto a particularly valuable and scarce resource (such as a database connection or file handle), you might not want to wait until the next garbage collection to clean up a class instance that's no longer in use. A class may implement the IDisposable interface to provide a way to release resources before a garbage collection. A class that implements that interface exposes a Dispose method that can be called to force valuable resources to be released immediately.

The Using statement automates the process of acquiring a resource, executing a set of statements, and then disposing of the resource. However, the resource must implement the IDisposable interface. For more information, see Using Statement.

See also

Event Statement

Declares a user-defined event.

Syntax

[ <attrlist> ] [ accessmodifier ] _  
[ Shared ] [ Shadows ] Event eventname[(parameterlist)] _  
[ Implements implementslist ]  
' -or-  
[ <attrlist> ] [ accessmodifier ] _  
[ Shared ] [ Shadows ] Event eventname As delegatename _  
[ Implements implementslist ]  
' -or-  
 [ <attrlist> ] [ accessmodifier ] _  
[ Shared ] [ Shadows ] Custom Event eventname As delegatename _  
[ Implements implementslist ]  
   [ <attrlist> ] AddHandler(ByVal value As delegatename)  
      [ statements ]  
   End AddHandler  
   [ <attrlist> ] RemoveHandler(ByVal value As delegatename)  
      [ statements ]  
   End RemoveHandler  
   [ <attrlist> ] RaiseEvent(delegatesignature)  
      [ statements ]  
   End RaiseEvent  
End Event  

Parts

Part Description
attrlist Optional. List of attributes that apply to this event. Multiple attributes are separated by commas. You must enclose the Attribute List in angle brackets ("<" and ">").
accessmodifier Optional. Specifies what code can access the event. Can be one of the following:

- Public—any code that can access the element that declares it can access it.
- Protected—only code within its class or a derived class can access it.
- Friend—only code in the same assembly can access it.
- Private—only code in the element that declares it can access it.
- Protected Friend-only code in the event's class, a derived class, or the same assembly can access it.
- Private Protected-only code in the event's class or a derived class in the same assembly can access it.
Shared Optional. Specifies that this event is not associated with a specific instance of a class or structure.
Shadows Optional. Indicates that this event redeclares and hides an identically named programming element, or set of overloaded elements, in a base class. You can shadow any kind of declared element with any other kind.

A shadowed element is unavailable from within the derived class that shadows it, except from where the shadowing element is inaccessible. For example, if a Private element shadows a base-class element, code that does not have permission to access the Private element accesses the base-class element instead.
eventname Required. Name of the event; follows standard variable naming conventions.
parameterlist Optional. List of local variables that represent the parameters of this event. You must enclose the Parameter List in parentheses.
Implements Optional. Indicates that this event implements an event of an interface.
implementslist Required if Implements is supplied. List of Sub procedures being implemented. Multiple procedures are separated by commas:

implementedprocedure [ , implementedprocedure ... ]

Each implementedprocedure has the following syntax and parts:

interface.definedname

- interface - Required. Name of an interface that this procedure's containing class or structure is implementing.
- Definedname - Required. Name by which the procedure is defined in interface. This does not have to be the same as name, the name that this procedure is using to implement the defined procedure.
Custom Required. Events declared as Custom must define custom AddHandler, RemoveHandler, and RaiseEvent accessors.
delegatename Optional. The name of a delegate that specifies the event-handler signature.
AddHandler Required. Declares an AddHandler accessor, which specifies the statements to execute when an event handler is added, either explicitly by using the AddHandler statement or implicitly by using the Handles clause.
End AddHandler Required. Terminates the AddHandler block.
value Required. Parameter name.
RemoveHandler Required. Declares a RemoveHandler accessor, which specifies the statements to execute when an event handler is removed using the RemoveHandler statement.
End RemoveHandler Required. Terminates the RemoveHandler block.
RaiseEvent Required. Declares a RaiseEvent accessor, which specifies the statements to execute when the event is raised using the RaiseEvent statement. Typically, this invokes a list of delegates maintained by the AddHandler and RemoveHandler accessors.
End RaiseEvent Required. Terminates the RaiseEvent block.
delegatesignature Required. List of parameters that matches the parameters required by the delegatename delegate. You must enclose the Parameter List in parentheses.
statements Optional. Statements that contain the bodies of the AddHandler, RemoveHandler, and RaiseEvent methods.
End Event Required. Terminates the Event block.

Remarks

Once the event has been declared, use the RaiseEvent statement to raise the event. A typical event might be declared and raised as shown in the following fragments:

VB
Public Class EventSource
    ' Declare an event.
    Public Event LogonCompleted(ByVal UserName As String)
    Sub CauseEvent()
        ' Raise an event on successful logon.
        RaiseEvent LogonCompleted("AustinSteele")
    End Sub
End Class

Note

You can declare event arguments just as you do arguments of procedures, with the following exceptions: events cannot have named arguments, ParamArray arguments, or Optional arguments. Events do not have return values.

To handle an event, you must associate it with an event handler subroutine using either the Handles or AddHandler statement. The signatures of the subroutine and the event must match. To handle a shared event, you must use the AddHandler statement.

You can use Event only at module level. This means the declaration context for an event must be a class, structure, module, or interface, and cannot be a source file, namespace, procedure, or block. For more information, see Declaration Contexts and Default Access Levels.

In most circumstances, you can use the first syntax in the Syntax section of this topic for declaring events. However, some scenarios require that you have more control over the detailed behavior of the event. The last syntax in the Syntax section of this topic, which uses the Custom keyword, provides that control by enabling you to define custom events. In a custom event, you specify exactly what occurs when code adds or removes an event handler to or from the event, or when code raises the event. For examples, see How to: Declare Custom Events To Conserve Memory and How to: Declare Custom Events To Avoid Blocking.

Note

The My.Application.DoEvents method does not process events in the same way the form does. To enable the form to handle the events directly, you can use multithreading. For more information, see Managed Threading.

See also

Implements Statement

Specifies one or more interfaces, or interface members, that must be implemented in the class or structure definition in which it appears.

Syntax

Implements interfacename [, ...]  
-or-  
Implements interfacename.interfacemember [, ...]  

Parts

interfacename
Required. An interface whose properties, procedures, and events are to be implemented by corresponding members in the class or structure.

interfacemember
Required. The member of an interface that is being implemented.

Remarks

An interface is a collection of prototypes representing the members (properties, procedures, and events) the interface encapsulates. Interfaces contain only the declarations for members; classes and structures implement these members. For more information, see Interfaces.

The Implements statement must immediately follow the Class or Structure statement.

When you implement an interface, you must implement all the members declared in the interface. Omitting any member is considered to be a syntax error. To implement an individual member, you specify the Implements keyword (which is separate from the Implements statement) when you declare the member in the class or structure. For more information, see Interfaces.

Classes can use Private implementations of properties and procedures, but these members are accessible only by casting an instance of the implementing class into a variable declared to be of the type of the interface.

See also

Imports Statement (.NET Namespace and Type)

Enables type names to be referenced without namespace qualification.

Syntax

Imports [ aliasname = ] namespace  
-or-  
Imports [ aliasname = ] namespace.element  

Parts

Term Definition
aliasname Optional. An import alias or name by which code can refer to namespace instead of the full qualification string. See Declared Element Names.
namespace Required. The fully qualified name of the namespace being imported. Can be a string of namespaces nested to any level.
element Optional. The name of a programming element declared in the namespace. Can be any container element.

Remarks

The Imports statement enables types that are contained in a given namespace to be referenced directly.

You can supply a single namespace name or a string of nested namespaces. Each nested namespace is separated from the next higher level namespace by a period (.), as the following example illustrates.

Imports System.Collections.Generic

Each source file can contain any number of Imports statements. These must follow any option declarations, such as the Option Strict statement, and they must precede any programming element declarations, such as Module or Class statements.

You can use Imports only at file level. This means the declaration context for importation must be a source file, and cannot be a namespace, class, structure, module, interface, procedure, or block.

Note that the Imports statement does not make elements from other projects and assemblies available to your project. Importing does not take the place of setting a reference. It only removes the need to qualify names that are already available to your project. For more information, see "Importing Containing Elements" in References to Declared Elements.

Note

You can define implicit Imports statements by using the References Page, Project Designer (Visual Basic). For more information, see How to: Add or Remove Imported Namespaces (Visual Basic).

Import Aliases

An import alias defines the alias for a namespace or type. Import aliases are useful when you need to use items with the same name that are declared in one or more namespaces. For more information and an example, see "Qualifying an Element Name" in References to Declared Elements.

You should not declare a member at module level with the same name as aliasname. If you do, the Visual Basic compiler uses aliasname only for the declared member and no longer recognizes it as an import alias.

Although the syntax used for declaring an import alias is like that used for importing an XML namespace prefix, the results are different. An import alias can be used as an expression in your code, whereas an XML namespace prefix can be used only in XML literals or XML axis properties as the prefix for a qualified element or attribute name.

Element Names

If you supply element, it must represent a container element, that is, a programming element that can contain other elements. Container elements include classes, structures, modules, interfaces, and enumerations.

The scope of the elements made available by an Imports statement depends on whether you specify element. If you specify only namespace, all uniquely named members of that namespace, and members of container elements within that namespace, are available without qualification. If you specify both namespace and element, only the members of that element are available without qualification.

See also

Imports Statement (XML Namespace)

Imports XML namespace prefixes for use in XML literals and XML axis properties.

Syntax

Imports <xmlns:xmlNamespacePrefix = "xmlNamespaceName">  

Parts

xmlNamespacePrefix
Optional. The string by which XML elements and attributes can refer to xmlNamespaceName. If no xmlNamespacePrefix is supplied, the imported XML namespace is the default XML namespace. Must be a valid XML identifier. For more information, see Names of Declared XML Elements and Attributes.

xmlNamespaceName
Required. The string identifying the XML namespace being imported.

Remarks

You can use the Imports statement to define global XML namespaces that you can use with XML literals and XML axis properties, or as parameters passed to the GetXmlNamespace operator. (For information about using the Imports statement to import an alias that can be used where type names are used in your code, see Imports Statement (.NET Namespace and Type).) The syntax for declaring an XML namespace by using the Imports statement is identical to the syntax used in XML. Therefore, you can copy a namespace declaration from an XML file and use it in an Imports statement.

XML namespace prefixes are useful when you want to repeatedly create XML elements that are from the same namespace. The XML namespace prefix declared with the Imports statement is global in the sense that it is available to all code in the file. You can use it when you create XML element literals and when you access XML axis properties. For more information, see XML Element Literal and XML Axis Properties.

If you define a global XML namespace without a namespace prefix (for example, Imports <xmlns="http://SomeNameSpace>"), that namespace is considered the default XML namespace. The default XML namespace is used for any XML element literals or XML attribute axis properties that do not explicitly specify a namespace. The default namespace is also used if the specified namespace is the empty namespace (that is, xmlns=""). The default XML namespace does not apply to XML attributes in XML literals or to XML attribute axis properties that do not have a namespace.

XML namespaces that are defined in an XML literal, which are called local XML namespaces, take precedence over XML namespaces that are defined by the Imports statement as global. XML namespaces that are defined by the Imports statement take precedence over XML namespaces imported for a Visual Basic project. If an XML literal defines an XML namespace, that local namespace does not apply to embedded expressions.

Global XML namespaces follow the same scoping and definition rules as .NET Framework namespaces. As a result, you can include an Imports statement to define a global XML namespace anywhere you can import a .NET Framework namespace. This includes both code files and project-level imported namespaces. For information about project-level imported namespaces, see References Page, Project Designer (Visual Basic).

Each source file can contain any number of Imports statements. These must follow option declarations, such as the Option Strict statement, and they must precede programming element declarations, such as Module or Class statements.

See also

Inherits Statement

Causes the current class or interface to inherit the attributes, variables, properties, procedures, and events from another class or set of interfaces.

Syntax

Inherits basetypenames  

Parts

Term Definition
basetypenames Required. The name of the class from which this class derives.

-or-

The names of the interfaces from which this interface derives. Use commas to separate multiple names.

Remarks

If used, the Inherits statement must be the first non-blank, non-comment line in a class or interface definition. It should immediately follow the Class or Interface statement.

You can use Inherits only in a class or interface. This means the declaration context for an inheritance cannot be a source file, namespace, structure, module, procedure, or block.

Rules

  • Class Inheritance. If a class uses the Inherits statement, you can specify only one base class.

    A class cannot inherit from a class nested within it.

  • Interface Inheritance. If an interface uses the Inherits statement, you can specify one or more base interfaces. You can inherit from two interfaces even if they each define a member with the same name. If you do so, the implementing code must use name qualification to specify which member it is implementing.

    An interface cannot inherit from another interface with a more restrictive access level. For example, a Public interface cannot inherit from a Friend interface.

    An interface cannot inherit from an interface nested within it.

An example of class inheritance in the .NET Framework is the ArgumentException class, which inherits from the SystemException class. This provides to ArgumentException all the predefined properties and procedures required by system exceptions, such as the Message property and the ToString method.

An example of interface inheritance in the .NET Framework is the ICollection interface, which inherits from the IEnumerable interface. This causes ICollection to inherit the definition of the enumerator required to traverse a collection.

See also

Interface Statement

Declares the name of an interface and introduces the definitions of the members that the interface comprises.

Syntax

[ <attributelist> ] [ accessmodifier ] [ Shadows ] _  
Interface name [ ( Of typelist ) ]  
    [ Inherits interfacenames ]  
    [ [ modifiers ] Property membername ]  
    [ [ modifiers ] Function membername ]  
    [ [ modifiers ] Sub membername ]  
    [ [ modifiers ] Event membername ]  
    [ [ modifiers ] Interface membername ]  
    [ [ modifiers ] Class membername ]  
    [ [ modifiers ] Structure membername ]  
End Interface  

Parts

Term Definition
attributelist Optional. See Attribute List.
accessmodifier Optional. Can be one of the following:

- Public
- Protected
- Friend
- Private
- Protected Friend
- Private Protected

See Access levels in Visual Basic.
Shadows Optional. See Shadows.
name Required. Name of this interface. See Declared Element Names.
Of Optional. Specifies that this is a generic interface.
typelist Required if you use the Of keyword. List of type parameters for this interface. Optionally, each type parameter can be declared variant by using In and Out generic modifiers. See Type List.
Inherits Optional. Indicates that this interface inherits the attributes and members of another interface or interfaces. See Inherits Statement.
interfacenames Required if you use the Inherits statement. The names of the interfaces from which this interface derives.
modifiers Optional. Appropriate modifiers for the interface member being defined.
Property Optional. Defines a property that is a member of the interface.
Function Optional. Defines a Function procedure that is a member of the interface.
Sub Optional. Defines a Sub procedure that is a member of the interface.
Event Optional. Defines an event that is a member of the interface.
Interface Optional. Defines an interface that is a nested within this interface. The nested interface definition must terminate with an End Interface statement.
Class Optional. Defines a class that is a member of the interface. The member class definition must terminate with an End Class statement.
Structure Optional. Defines a structure that is a member of the interface. The member structure definition must terminate with an End Structure statement.
membername Required for each property, procedure, event, interface, class, or structure defined as a member of the interface. The name of the member.
End Interface Terminates the Interface definition.

Remarks

An interface defines a set of members, such as properties and procedures, that classes and structures can implement. The interface defines only the signatures of the members and not their internal workings.

A class or structure implements the interface by supplying code for every member defined by the interface. Finally, when the application creates an instance from that class or structure, an object exists and runs in memory. For more information, see Objects and Classes and Interfaces.

You can use Interface only at namespace or module level. This means the declaration context for an interface must be a source file, namespace, class, structure, module, or interface, and cannot be a procedure or block. For more information, see Declaration Contexts and Default Access Levels.

Interfaces default to Friend access. You can adjust their access levels with the access modifiers. For more information, see Access levels in Visual Basic.

Rules

  • Nesting Interfaces. You can define one interface within another. The outer interface is called the containing interface, and the inner interface is called a nested interface.

  • Member Declaration. When you declare a property or procedure as a member of an interface, you are defining only the signature of that property or procedure. This includes the element type (property or procedure), its parameters and parameter types, and its return type. Because of this, the member definition uses only one line of code, and terminating statements such as End Function or End Property are not valid in an interface.

    In contrast, when you define an enumeration or structure, or a nested class or interface, it is necessary to include their data members.

  • Member Modifiers. You cannot use any access modifiers when defining module members, nor can you specify Shared or any procedure modifier except Overloads. You can declare any member with Shadows, and you can use Default when defining a property, as well as ReadOnly or WriteOnly.

  • Inheritance. If the interface uses the Inherits Statement, you can specify one or more base interfaces. You can inherit from two interfaces even if they each define a member with the same name. If you do so, the implementing code must use name qualification to specify which member it is implementing.

    An interface cannot inherit from another interface with a more restrictive access level. For example, a Public interface cannot inherit from a Friend interface.

    An interface cannot inherit from an interface nested within it.

  • Implementation. When a class uses the Implements statement to implement this interface, it must implement every member defined within the interface. Furthermore, each signature in the implementing code must exactly match the corresponding signature defined in this interface. However, the name of the member in the implementing code does not have to match the member name as defined in the interface.

    When a class is implementing a procedure, it cannot designate the procedure as Shared.

  • Default Property. An interface can specify at most one property as its default property, which can be referenced without using the property name. You specify such a property by declaring it with the Default modifier.

    Notice that this means that an interface can define a default property only if it inherits none.

Behavior

  • Access Level. All interface members implicitly have Public access. You cannot use any access modifier when defining a member. However, a class implementing the interface can declare an access level for each implemented member.

    If you assign a class instance to a variable, the access level of its members can depend on whether the data type of the variable is the underlying interface or the implementing class.

    If you access class members through varAsInterface, they all have public access. However, if you access members through varAsClass, the Sub procedure doSomething has private access.

  • Scope. An interface is in scope throughout its namespace, class, structure, or module.

    The scope of every interface member is the entire interface.

  • Lifetime. An interface does not itself have a lifetime, nor do its members. When a class implements an interface and an object is created as an instance of that class, the object has a lifetime within the application in which it is running. For more information, see "Lifetime" in Class Statement.

Note that the Property and Function statements do not introduce blocks ending with End Property and End Function within the interface. The interface defines only the signatures of its members. The full Property and Function blocks appear in a class that implements thisInterface.

See also

Namespace Statement

Declares the name of a namespace and causes the source code that follows the declaration to be compiled within that namespace.

Syntax

VB
Namespace [Global.] { name | name.name }  
    [ componenttypes ]  
End Namespace  

Parts

Global
Optional. Allows you to define a namespace out of the root namespace of your project. See Namespaces in Visual Basic.

name
Required. A unique name that identifies the namespace. Must be a valid Visual Basic identifier. For more information, see Declared Element Names.

componenttypes
Optional. Elements that make up the namespace. These include, but are not limited to, enumerations, structures, interfaces, classes, modules, delegates, and other namespaces.

End Namespace
Terminates a Namespace block.

Remarks

Namespaces are used as an organizational system. They provide a way to classify and present programming elements that are exposed to other programs and applications. Note that a namespace is not a type in the sense that a class or structure is—you cannot declare a programming element to have the data type of a namespace.

All programming elements declared after a Namespace statement belong to that namespace. Visual Basic continues to compile elements into the last declared namespace until it encounters either an End Namespace statement or another Namespace statement.

If a namespace is already defined, even outside your project, you can add programming elements to it. To do this, you use a Namespace statement to direct Visual Basic to compile elements into that namespace.

You can use a Namespace statement only at the file or namespace level. This means the declaration context for a namespace must be a source file or another namespace, and cannot be a class, structure, module, interface, or procedure. For more information, see Declaration Contexts and Default Access Levels.

You can declare one namespace within another. There is no strict limit to the levels of nesting you can declare, but remember that when other code accesses the elements declared in the innermost namespace, it must use a qualification string that contains all the namespace names in the nesting hierarchy.

Access Level

Namespaces are treated as if they have a Public access level. A namespace can be accessed from code anywhere in the same project, from other projects that reference the project, and from any assembly built from the project.

Programming elements declared at namespace level, meaning in a namespace but not inside any other element, can have Public or Friend access. If unspecified, the access level of such an element uses Friend by default. Elements you can declare at namespace level include classes, structures, modules, interfaces, enumerations, and delegates. For more information, see Declaration Contexts and Default Access Levels.

Root Namespace

All namespace names in your project are based on a root namespace. Visual Studio assigns your project name as the default root namespace for all code in your project. For example, if your project is named Payroll, its programming elements belong to namespace Payroll. If you declare Namespace funding, the full name of that namespace is Payroll.funding.

If you want to specify an existing namespace in a Namespace statement, such as in the generic list class example, you can set your root namespace to a null value. To do this, click Project Properties from the Project menu and then clear the Root namespace entry so that the box is empty. If you did not do this in the generic list class example, the Visual Basic compiler would take System.Collections.Generic as a new namespace within project Payroll, with the full name of Payroll.System.Collections.Generic.

Alternatively, you can use the Global keyword to refer to elements of namespaces defined outside your project. Doing so lets you retain your project name as the root namespace. This reduces the chance of unintentionally merging your programming elements together with those of existing namespaces. For more information, see the "Global Keyword in Fully Qualified Names" section in Namespaces in Visual Basic.

The Global keyword can also be used in a Namespace statement. This lets you define a namespace out of the root namespace of your project. For more information, see the "Global Keyword in Namespace Statements" section in Namespaces in Visual Basic.

Troubleshooting. The root namespace can lead to unexpected concatenations of namespace names. If you make reference to namespaces defined outside your project, the Visual Basic compiler can construe them as nested namespaces in the root namespace. In such a case, the compiler does not recognize any types that have been already defined in the external namespaces. To avoid this, either set your root namespace to a null value as described in "Root Namespace," or use the Global keyword to access elements of external namespaces.

Attributes and Modifiers

You cannot apply attributes to a namespace. An attribute contributes information to the assembly's metadata, which is not meaningful for source classifiers such as namespaces.

You cannot apply any access or procedure modifiers, or any other modifiers, to a namespace. Because it is not a type, these modifiers are not meaningful.

See also

ReDim Statement

Reallocates storage space for an array variable.

Syntax

ReDim [ Preserve ] name(boundlist) [ ,  name(boundlist) [, ... ] ]  

Parts

Term Definition
Preserve Optional. Modifier used to preserve the data in the existing array when you change the size of only the last dimension.
name Required. Name of the array variable. See Declared Element Names.
boundlist Required. List of bounds of each dimension of the redefined array.

Remarks

You can use the ReDim statement to change the size of one or more dimensions of an array that has already been declared. If you have a large array and you no longer need some of its elements, ReDim can free up memory by reducing the array size. On the other hand, if your array needs more elements, ReDim can add them.

The ReDim statement is intended only for arrays. It's not valid on scalars (variables that contain only a single value), collections, or structures. Note that if you declare a variable to be of type Array, the ReDim statement doesn't have sufficient type information to create the new array.

You can use ReDim only at procedure level. Therefore, the declaration context for the variable must be a procedure; it can't be a source file, a namespace, an interface, a class, a structure, a module, or a block. For more information, see Declaration Contexts and Default Access Levels.

Rules

  • Multiple Variables. You can resize several array variables in the same declaration statement and specify the name and boundlist parts for each variable. Multiple variables are separated by commas.

  • Array Bounds. Each entry in boundlist can specify the lower and upper bounds of that dimension. The lower bound is always 0 (zero). The upper bound is the highest possible index value for that dimension, not the length of the dimension (which is the upper bound plus one). The index for each dimension can vary from 0 through its upper bound value.

    The number of dimensions in boundlist must match the original number of dimensions (rank) of the array.

  • Data Types. The ReDim statement cannot change the data type of an array variable or its elements.

  • Initialization. The ReDim statement cannot provide new initialization values for the array elements.

  • Rank. The ReDim statement cannot change the rank (the number of dimensions) of the array.

  • Resizing with Preserve. If you use Preserve, you can resize only the last dimension of the array. For every other dimension, you must specify the bound of the existing array.

    For example, if your array has only one dimension, you can resize that dimension and still preserve all the contents of the array, because you are changing the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension if you use Preserve.

  • Properties. You can use ReDim on a property that holds an array of values.

Behavior

  • Array Replacement. ReDim releases the existing array and creates a new array with the same rank. The new array replaces the released array in the array variable.

  • Initialization without Preserve. If you do not specify Preserve, ReDim initializes the elements of the new array by using the default value for their data type.

  • Initialization with Preserve. If you specify Preserve, Visual Basic copies the elements from the existing array to the new array.

See also

Source/Reference


©sideway

ID: 200800010 Last Updated: 8/10/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