Sideway
output.to from Sideway
Draft for Information Only

Content

VB.NET Procedure Block Statements
  Class Statement
  Syntax
  Parts
  Remarks
  Rules
  Behavior
  Classes and Modules
  See also
  Function Statement
  Syntax
  Parts
  Remarks
  Defining a Function
  Returning from a Function
  Calling a Function
  Async Functions
  Iterator Functions
  See also
  Get Statement
  Syntax
  Parts
  Remarks
  Rules
  Behavior
  See also
  Module Statement
  Syntax
  Parts
  Remarks
  Classes and Modules
  Rules
  Behavior
  See also
  Operator Statement
  Syntax
  Parts
  Remarks
  Matched Pairs
  Data Type Restrictions
  Logical and Bitwise Operators
  Widening and Narrowing Conversions
  See also
  Property Statement
  Syntax
  Parts
  Remarks
  Rules
  Behavior
  See also
  Structure Statement
  Syntax
  Parts
  Remarks
  Rules
  Behavior
  See also
  Sub Statement
  Syntax
  Parts
  Remarks
  Defining a Sub Procedure
  Returning from a Sub Procedure
  Calling a Sub Procedure
  Async Sub Procedures
  See also
  SyncLock Statement
  Syntax
  Parts
  Remarks
  Rules
  Behavior
  Programming Practices
  Comments
  See also
  Using Statement
  Syntax
  Parts
  resourcelist Parts
  Remarks
  Behavior
  Structured Exception Handling Within a Using Block
  Structured Exception Handling Instead of a Using Block
  See also
  With...End With Statement
  Syntax
  Parts
  Remarks
  See also
 Source/Reference

VB.NET Procedure Block Statements

The supporting VB.NET Procedure Block Statements are Class, Function, Get, Module, Operator, Property,               Property Get, Property Let, Property Set,SyncLock, Sub, Using, With...End With

Class Statement

Declares the name of a class and introduces the definition of the variables, properties, events, and procedures that the class comprises.

Syntax

[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _  
Class name [ ( Of typelist ) ]  
    [ Inherits classname ]  
    [ Implements interfacenames ]  
    [ statements ]  
End Class  

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.
MustInherit Optional. See MustInherit.
NotInheritable Optional. See NotInheritable.
Partial Optional. Indicates a partial definition of the class. See Partial.
name Required. Name of this class. See Declared Element Names.
Of Optional. Specifies that this is a generic class.
typelist Required if you use the Of keyword. List of type parameters for this class. See Type List.
Inherits Optional. Indicates that this class inherits the members of another class. See Inherits Statement.
classname Required if you use the Inherits statement. The name of the class from which this class derives.
Implements Optional. Indicates that this class implements the members of one or more interfaces. See Implements Statement.
interfacenames Required if you use the Implements statement. The names of the interfaces this class implements.
statements Optional. Statements which define the members of this class.
End Class Required. Terminates the Class definition.

Remarks

A Class statement defines a new data type. A class is a fundamental building block of object-oriented programming (OOP). For more information, see Objects and Classes.

You can use Class only at namespace or module level. This means the declaration context for a class 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.

Each instance of a class has a lifetime independent of all other instances. This lifetime begins when it is created by a New Operator clause or by a function such as CreateObject. It ends when all variables pointing to the instance have been set to Nothing or to instances of other classes.

Classes 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. You can define one class within another. The outer class is called the containing class, and the inner class is called a nested class.

  • Inheritance. If the class uses the Inherits Statement, you can specify only one base class or interface. A class cannot inherit from more than one element.

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

    A class cannot inherit from a class nested within it.

  • Implementation. If the class uses the Implements Statement, you must implement every member defined by every interface you specify in interfacenames. An exception to this is reimplementation of a base class member. For more information, see "Reimplementation" in Implements.

  • Default Property. A class can specify at most one property as its default property. For more information, see Default.

Behavior

  • Access Level. Within a class, you can declare each member with its own access level. Class members default to Public access, except variables and constants, which default to Private access. When a class has more restricted access than one of its members, the class access level takes precedence.

  • Scope. A class is in scope throughout its containing namespace, class, structure, or module.

    The scope of every class member is the entire class.

    Lifetime. Visual Basic does not support static classes. The functional equivalent of a static class is provided by a module. For more information, see Module Statement.

    Class members have lifetimes depending on how and where they are declared. For more information, see Lifetime in Visual Basic.

  • Qualification. Code outside a class must qualify a member's name with the name of that class.

    If code inside a nested class makes an unqualified reference to a programming element, Visual Basic searches for the element first in the nested class, then in its containing class, and so on out to the outermost containing element.

Classes and Modules

These elements have many similarities, but there are some important differences as well.

  • Terminology. Previous versions of Visual Basic recognize two types of modules: class modules (.cls files) and standard modules (.bas files). The current version calls these classes and modules, respectively.

  • Shared Members. You can control whether a member of a class is a shared or instance member.

  • Object Orientation. Classes are object-oriented, but modules are not. You can create one or more instances of a class. For more information, see Objects and Classes.

See also

Function Statement

Declares the name, parameters, and code that define a Function procedure.

Syntax

[ <attributelist> ] [ accessmodifier ] [ proceduremodifiers ] [ Shared ] [ Shadows ] [ Async | Iterator ]
Function name [ (Of typeparamlist) ] [ (parameterlist) ] [ As returntype ] [ Implements implementslist | Handles eventlist ]
    [ statements ]
    [ Exit Function ]
    [ statements ]
End Function

Parts

  • attributelist

    Optional. See Attribute List.

  • accessmodifier

    Optional. Can be one of the following:

    See Access levels in Visual Basic.

  • proceduremodifiers

    Optional. Can be one of the following:

  • Shared

    Optional. See Shared.

  • Shadows

    Optional. See Shadows.

  • Async

    Optional. See Async.

  • Iterator

    Optional. See Iterator.

  • name

    Required. Name of the procedure. See Declared Element Names.

  • typeparamlist

    Optional. List of type parameters for a generic procedure. See Type List.

  • parameterlist

    Optional. List of local variable names representing the parameters of this procedure. See Parameter List.

  • returntype

    Required if Option Strict is On. Data type of the value returned by this procedure.

  • Implements

    Optional. Indicates that this procedure implements one or more Function procedures, each one defined in an interface implemented by this procedure's containing class or structure. See Implements Statement.

  • implementslist

    Required if Implements is supplied. List of Function procedures being implemented.

    implementedprocedure [ , implementedprocedure ... ]

    Each implementedprocedure has the following syntax and parts:

    interface.definedname

    Part Description
    interface Required. Name of an interface implemented by this procedure's containing class or structure.
    definedname Required. Name by which the procedure is defined in interface.
  • Handles

    Optional. Indicates that this procedure can handle one or more specific events. See Handles.

  • eventlist

    Required if Handles is supplied. List of events this procedure handles.

    eventspecifier [ , eventspecifier ... ]

    Each eventspecifier has the following syntax and parts:

    eventvariable.event

    Part Description
    eventvariable Required. Object variable declared with the data type of the class or structure that raises the event.
    event Required. Name of the event this procedure handles.
  • statements

    Optional. Block of statements to be executed within this procedure.

  • End Function

    Terminates the definition of this procedure.

Remarks

All executable code must be inside a procedure. Each procedure, in turn, is declared within a class, a structure, or a module that is referred to as the containing class, structure, or module.

To return a value to the calling code, use a Function procedure; otherwise, use a Sub procedure.

Defining a Function

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

Function procedures default to public access. You can adjust their access levels with the access modifiers.

A Function procedure can declare the data type of the value that the procedure returns. You can specify any data type or the name of an enumeration, a structure, a class, or an interface. If you don't specify the returntype parameter, the procedure returns Object.

If this procedure uses the Implements keyword, the containing class or structure must also have an Implements statement that immediately follows its Class or Structure statement. The Implements statement must include each interface that's specified in implementslist. However, the name by which an interface defines the Function (in definedname) doesn't need to match the name of this procedure (in name).

Note

You can use lambda expressions to define function expressions inline. For more information, see Function Expression and Lambda Expressions.

Returning from a Function

When the Function procedure returns to the calling code, execution continues with the statement that follows the statement that called the procedure.

To return a value from a function, you can either assign the value to the function name or include it in a Return statement.

The Return statement simultaneously assigns the return value and exits the function, as the following example shows.

VB
Function MyFunction(ByVal j As Integer) As Double
    Return 3.87 * j
End Function

The following example assigns the return value to the function name myFunction and then uses the Exit Function statement to return.

VB
Function MyFunction(ByVal j As Integer) As Double
    MyFunction = 3.87 * j
    Exit Function
End Function

The Exit Function and Return statements cause an immediate exit from a Function procedure. Any number of Exit Function and Return statements can appear anywhere in the procedure, and you can mix Exit Function and Return statements.

If you use Exit Function without assigning a value to name, the procedure returns the default value for the data type that's specified in returntype. If returntype isn't specified, the procedure returns Nothing, which is the default value for Object.

Calling a Function

You call a Function procedure by using the procedure name, followed by the argument list in parentheses, in an expression. You can omit the parentheses only if you aren't supplying any arguments. However, your code is more readable if you always include the parentheses.

You call a Function procedure the same way that you call any library function such as Sqrt, Cos, or ChrW.

You can also call a function by using the Call keyword. In that case, the return value is ignored. Use of the Call keyword isn't recommended in most cases. For more information, see Call Statement.

Visual Basic sometimes rearranges arithmetic expressions to increase internal efficiency. For that reason, you shouldn't use a Function procedure in an arithmetic expression when the function changes the value of variables in the same expression.

Async Functions

The Async feature allows you to invoke asynchronous functions without using explicit callbacks or manually splitting your code across multiple functions or lambda expressions.

If you mark a function with the Async modifier, you can use the Await operator in the function. When control reaches an Await expression in the Async function, control returns to the caller, and progress in the function is suspended until the awaited task completes. When the task is complete, execution can resume in the function.

Note

An Async procedure returns to the caller when either it encounters the first awaited object that’s not yet complete, or it gets to the end of the Async procedure, whichever occurs first.

An Async function can have a return type of Task<TResult> or Task. An example of an Async function that has a return type of Task<TResult> is provided below.

An Async function cannot declare any ByRef parameters.

A Sub Statement can also be marked with the Async modifier. This is primarily used for event handlers, where a value cannot be returned. An Async Sub procedure can't be awaited, and the caller of an Async Sub procedure can't catch exceptions that are thrown by the Sub procedure.

For more information about Async functions, see Asynchronous Programming with Async and Await, Control Flow in Async Programs, and Async Return Types.

Iterator Functions

An iterator function performs a custom iteration over a collection, such as a list or array. An iterator function uses the Yield statement to return each element one at a time. When a Yield statement is reached, the current location in code is remembered. Execution is restarted from that location the next time the iterator function is called.

You call an iterator from client code by using a For Each…Next statement.

The return type of an iterator function can be IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>.

For more information, see Iterators.

See also

Get Statement

Declares a Get property procedure used to retrieve the value of a property.

Syntax

[ <attributelist> ] [ accessmodifier ] Get()  
    [ statements ]  
End Get  

Parts

Term Definition
attributelist Optional. See Attribute List.
accessmodifier Optional on at most one of the Get and Set statements in this property. Can be one of the following:

- Protected
- Friend
- Private
- Protected Friend

See Access levels in Visual Basic.
statements Optional. One or more statements that run when the Get property procedure is called.
End Get Required. Terminates the definition of the Get property procedure.

Remarks

Every property must have a Get property procedure unless the property is marked WriteOnly. The Get procedure is used to return the current value of the property.

Visual Basic automatically calls a property's Get procedure when an expression requests the property's value.

The body of the property declaration can contain only the property's Get and Set procedures between the Property Statement and the End Property statement. It cannot store anything other than those procedures. In particular, it cannot store the property's current value. You must store this value outside the property, because if you store it inside either of the property procedures, the other property procedure cannot access it. The usual approach is to store the value in a Private variable declared at the same level as the property. You must define a Get procedure inside the property to which it applies.

The Get procedure defaults to the access level of its containing property unless you use accessmodifier in the Get statement.

Rules

  • Mixed Access Levels. If you are defining a read-write property, you can optionally specify a different access level for either the Get or the Set procedure, but not both. If you do this, the procedure access level must be more restrictive than the property's access level. For example, if the property is declared Friend, you can declare the Get procedure Private, but not Public.

    If you are defining a ReadOnly property, the Get procedure represents the entire property. You cannot declare a different access level for Get, because that would set two access levels for the property.

  • Return Type. The Property Statement can declare the data type of the value it returns. The Get procedure automatically returns that data type. You can specify any data type or the name of an enumeration, structure, class, or interface.

    If the Property statement does not specify returntype, the procedure returns Object.

Behavior

  • Returning from a Procedure. When the Get procedure returns to the calling code, execution continues within the statement that requested the property value.

    Get property procedures can return a value using either the Return Statement or by assigning the return value to the property name. For more information, see "Return Value" in Function Statement.

    The Exit Property and Return statements cause an immediate exit from a property procedure. Any number of Exit Property and Return statements can appear anywhere in the procedure, and you can mix Exit Property and Return statements.

  • Return Value. To return a value from a Get procedure, you can either assign the value to the property name or include it in a Return Statement. The Return statement simultaneously assigns the Get procedure return value and exits the procedure.

    If you use Exit Property without assigning a value to the property name, the Get procedure returns the default value for the property's data type. For more information, see "Return Value" in Function Statement.

See also

Module Statement

Declares the name of a module and introduces the definition of the variables, properties, events, and procedures that the module comprises.

Syntax

VB
[ <attributelist> ] [ accessmodifier ]  Module name  
    [ statements ]  
End Module  

Parts

attributelist
Optional. See Attribute List.

accessmodifier
Optional. Can be one of the following:

See Access levels in Visual Basic.

name
Required. Name of this module. See Declared Element Names.

statements
Optional. Statements which define the variables, properties, events, procedures, and nested types of this module.

End Module
Terminates the Module definition.

Remarks

A Module statement defines a reference type available throughout its namespace. A module (sometimes called a standard module) is similar to a class but with some important distinctions. Every module has exactly one instance and does not need to be created or assigned to a variable. Modules do not support inheritance or implement interfaces. Notice that a module 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 module.

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

A module has the same lifetime as your program. Because its members are all Shared, they also have lifetimes equal to that of the program.

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

All members of a module are implicitly Shared.

Classes and Modules

These elements have many similarities, but there are some important differences as well.

  • Terminology. Previous versions of Visual Basic recognize two types of modules: class modules (.cls files) and standard modules (.bas files). The current version calls these classes and modules, respectively.

  • Shared Members. You can control whether a member of a class is a shared or instance member.

  • Object Orientation. Classes are object-oriented, but modules are not. So only classes can be instantiated as objects. For more information, see Objects and Classes.

Rules

  • Modifiers. All module members are implicitly Shared. You cannot use the Shared keyword when declaring a member, and you cannot alter the shared status of any member.

  • Inheritance. A module cannot inherit from any type other than Object, from which all modules inherit. In particular, one module cannot inherit from another.

    You cannot use the Inherits Statement in a module definition, even to specify Object.

  • Default Property. You cannot define any default properties in a module. For more information, see Default.

Behavior

  • Access Level. Within a module, you can declare each member with its own access level. Module members default to Public access, except variables and constants, which default to Private access. When a module has more restricted access than one of its members, the specified module access level takes precedence.

  • Scope. A module is in scope throughout its namespace.

    The scope of every module member is the entire module. Notice that all members undergo type promotion, which causes their scope to be promoted to the namespace containing the module. For more information, see Type Promotion.

  • Qualification. You can have multiple modules in a project, and you can declare members with the same name in two or more modules. However, you must qualify any reference to such a member with the appropriate module name if the reference is from outside that module. For more information, see References to Declared Elements.

See also

Operator Statement

Declares the operator symbol, operands, and code that define an operator procedure on a class or structure.

Syntax

[ <attrlist> ] Public [ Overloads ] Shared [ Shadows ] [ Widening | Narrowing ]   
Operator operatorsymbol ( operand1 [, operand2 ]) [ As [ <attrlist> ] type ]  
    [ statements ]  
    [ statements ]  
    Return returnvalue  
    [ statements ]  
End Operator  

Parts

attrlist
Optional. See Attribute List.

Public
Required. Indicates that this operator procedure has Public access.

Overloads
Optional. See Overloads.

Shared
Required. Indicates that this operator procedure is a Shared procedure.

Shadows
Optional. See Shadows.

Widening
Required for a conversion operator unless you specify Narrowing. Indicates that this operator procedure defines a Widening conversion. See "Widening and Narrowing Conversions" on this Help page.

Narrowing
Required for a conversion operator unless you specify Widening. Indicates that this operator procedure defines a Narrowing conversion. See "Widening and Narrowing Conversions" on this Help page.

operatorsymbol
Required. The symbol or identifier of the operator that this operator procedure defines.

operand1
Required. The name and type of the single operand of a unary operator (including a conversion operator) or the left operand of a binary operator.

operand2
Required for binary operators. The name and type of the right operand of a binary operator.

operand1 and operand2 have the following syntax and parts:

[ ByVal ] operandname [ As operandtype ]

Part Description
ByVal Optional, but the passing mechanism must be ByVal.
operandname Required. Name of the variable representing this operand. See Declared Element Names.
operandtype Optional unless Option Strict is On. Data type of this operand.

type
Optional unless Option Strict is On. Data type of the value the operator procedure returns.

statements
Optional. Block of statements that the operator procedure runs.

returnvalue
Required. The value that the operator procedure returns to the calling code.

End Operator
Required. Terminates the definition of this operator procedure.

Remarks

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

All operators must be Public Shared. You cannot specify ByRef, Optional, or ParamArray for either operand.

You cannot use the operator symbol or identifier to hold a return value. You must use the Return statement, and it must specify a value. Any number of Return statements can appear anywhere in the procedure.

Defining an operator in this way is called operator overloading, whether or not you use the Overloads keyword. The following table lists the operators you can define.

Type Operators
Unary +, -, IsFalse, IsTrue, Not
Binary +, -, *, /, \, &, ^, >>, <<, =, <>, >, >=, <, <=, And, Like, Mod, Or, Xor
Conversion (unary) CType

Note that the = operator in the binary list is the comparison operator, not the assignment operator.

When you define CType, you must specify either Widening or Narrowing.

Matched Pairs

You must define certain operators as matched pairs. If you define either operator of such a pair, you must define the other as well. The matched pairs are the following:

  • = and <>

  • > and <

  • >= and <=

  • IsTrue and IsFalse

Data Type Restrictions

Every operator you define must involve the class or structure on which you define it. This means that the class or structure must appear as the data type of the following:

  • The operand of a unary operator.

  • At least one of the operands of a binary operator.

  • Either the operand or the return type of a conversion operator.

Certain operators have additional data type restrictions, as follows:

  • If you define the IsTrue and IsFalse operators, they must both return the Boolean type.

  • If you define the << and >> operators, they must both specify the Integer type for the operandtype of operand2.

The return type does not have to correspond to the type of either operand. For example, a comparison operator such as = or <> can return Boolean even if neither operand is Boolean.

Logical and Bitwise Operators

The And, Or, Not, and Xor operators can perform either logical or bitwise operations in Visual Basic. However, if you define one of these operators on a class or structure, you can define only its bitwise operation.

You cannot define the AndAlso operator directly with an Operator statement. However, you can use AndAlso if you have fulfilled the following conditions:

  • You have defined And on the same operand types you want to use for AndAlso.

  • Your definition of And returns the same type as the class or structure on which you have defined it.

  • You have defined the IsFalse operator on the class or structure on which you have defined And.

Similarly, you can use OrElse if you have defined Or on the same operands, with the return type of the class or structure, and you have defined IsTrue on the class or structure.

Widening and Narrowing Conversions

A widening conversion always succeeds at run time, while a narrowing conversion can fail at run time. For more information, see Widening and Narrowing Conversions.

If you declare a conversion procedure to be Widening, your procedure code must not generate any failures. This means the following:

  • It must always return a valid value of type type.

  • It must handle all possible exceptions and other error conditions.

  • It must handle any error returns from any procedures it calls.

If there is any possibility that a conversion procedure might not succeed, or that it might cause an unhandled exception, you must declare it to be Narrowing.

See also

Property Statement

Declares the name of a property, and the property procedures used to store and retrieve the value of the property.

Syntax

VB
[ <attributelist> ] [ Default ] [ accessmodifier ]
[ propertymodifiers ] [ Shared ] [ Shadows ] [ ReadOnly | WriteOnly ] [ Iterator ]
Property name ( [ parameterlist ] ) [ As returntype ] [ Implements implementslist ]
    [ <attributelist> ] [ accessmodifier ] Get
        [ statements ]
    End Get
    [ <attributelist> ] [ accessmodifier ] Set ( ByVal value As returntype [, parameterlist ] )
        [ statements ]
    End Set
End Property
- or -
[ <attributelist> ] [ Default ] [ accessmodifier ]
[ propertymodifiers ] [ Shared ] [ Shadows ] [ ReadOnly | WriteOnly ]
Property name ( [ parameterlist ] ) [ As returntype ] [ Implements implementslist ]

Parts

  • attributelist

    Optional. List of attributes that apply to this property or Get or Set procedure. See Attribute List.

  • Default

    Optional. Specifies that this property is the default property for the class or structure on which it is defined. Default properties must accept parameters and can be set and retrieved without specifying the property name. If you declare the property as Default, you cannot use Private on the property or on either of its property procedures.

  • accessmodifier

    Optional on the Property statement and on at most one of the Get and Set statements. Can be one of the following:

    See Access levels in Visual Basic.

  • propertymodifiers

    Optional. Can be one of the following:

  • Shared

    Optional. See Shared.

  • Shadows

    Optional. See Shadows.

  • ReadOnly

    Optional. See ReadOnly.

  • WriteOnly

    Optional. See WriteOnly.

  • Iterator

    Optional. See Iterator.

  • name

    Required. Name of the property. See Declared Element Names.

  • parameterlist

    Optional. List of local variable names representing the parameters of this property, and possible additional parameters of the Set procedure. See Parameter List.

  • returntype

    Required if Option Strict is On. Data type of the value returned by this property.

  • Implements

    Optional. Indicates that this property implements one or more properties, each one defined in an interface implemented by this property's containing class or structure. See Implements Statement.

  • implementslist

    Required if Implements is supplied. List of properties being implemented.

    implementedproperty [ , implementedproperty ... ]

    Each implementedproperty has the following syntax and parts:

    interface.definedname

    Part Description
    interface Required. Name of an interface implemented by this property's containing class or structure.
    definedname Required. Name by which the property is defined in interface.
  • Get

    Optional. Required if the property is marked WriteOnly. Starts a Get property procedure that is used to return the value of the property.

  • statements

    Optional. Block of statements to run within the Get or Set procedure.

  • End Get

    Terminates the Get property procedure.

  • Set

    Optional. Required if the property is marked ReadOnly. Starts a Set property procedure that is used to store the value of the property.

  • End Set

    Terminates the Set property procedure.

  • End Property

    Terminates the definition of this property.

Remarks

The Property statement introduces the declaration of a property. A property can have a Get procedure (read only), a Set procedure (write only), or both (read-write). You can omit the Get and Set procedure when using an auto-implemented property. For more information, see Auto-Implemented Properties.

You can use Property only at class level. This means the declaration context for a property 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.

By default, properties use public access. You can adjust a property's access level with an access modifier on the Property statement, and you can optionally adjust one of its property procedures to a more restrictive access level.

Visual Basic passes a parameter to the Set procedure during property assignments. If you do not supply a parameter for Set, the integrated development environment (IDE) uses an implicit parameter named value. This parameter holds the value to be assigned to the property. You typically store this value in a private local variable and return it whenever the Get procedure is called.

Rules

  • Mixed Access Levels. If you are defining a read-write property, you can optionally specify a different access level for either the Get or the Set procedure, but not both. If you do this, the procedure access level must be more restrictive than the property's access level. For example, if the property is declared Friend, you can declare the Set procedure Private, but not Public.

    If you are defining a ReadOnly or WriteOnly property, the single property procedure (Get or Set, respectively) represents all of the property. You cannot declare a different access level for such a procedure, because that would set two access levels for the property.

  • Return Type. The Property statement can declare the data type of the value it returns. You can specify any data type or the name of an enumeration, structure, class, or interface.

    If you do not specify returntype, the property returns Object.

  • Implementation. If this property uses the Implements keyword, the containing class or structure must have an Implements statement immediately following its Class or Structure statement. The Implements statement must include each interface specified in implementslist. However, the name by which an interface defines the Property (in definedname) does not have to be the same as the name of this property (in name).

Behavior

  • Returning from a Property Procedure. When the Get or Set procedure returns to the calling code, execution continues with the statement following the statement that invoked it.

    The Exit Property and Return statements cause an immediate exit from a property procedure. Any number of Exit Property and Return statements can appear anywhere in the procedure, and you can mix Exit Property and Return statements.

  • Return Value. To return a value from a Get procedure, you can either assign the value to the property name or include it in a Return statement. The following example assigns the return value to the property name quoteForTheDay and then uses the Exit Property statement to return.

    VB
Private quoteValue As String = "No quote assigned yet."
VB
ReadOnly Property QuoteForTheDay() As String
    Get
        QuoteForTheDay = quoteValue
        Exit Property
    End Get
End Property

If you use Exit Property without assigning a value to name, the Get procedure returns the default value for the property's data type.

The Return statement at the same time assigns the Get procedure return value and exits the procedure. The following example shows this.

VB
Private quoteValue As String = "No quote assigned yet."
VB
ReadOnly Property QuoteForTheDay() As String
    Get
        Return quoteValue
    End Get
End Property

See also

Structure Statement

Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that the structure comprises.

Syntax

[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ Partial ] _  
Structure name [ ( Of typelist ) ]  
    [ Implements interfacenames ]  
    [ datamemberdeclarations ]  
    [ methodmemberdeclarations ]  
End Structure  

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.
Partial Optional. Indicates a partial definition of the structure. See Partial.
name Required. Name of this structure. See Declared Element Names.
Of Optional. Specifies that this is a generic structure.
typelist Required if you use the Of keyword. List of type parameters for this structure. See Type List.
Implements Optional. Indicates that this structure implements the members of one or more interfaces. See Implements Statement.
interfacenames Required if you use the Implements statement. The names of the interfaces this structure implements.
datamemberdeclarations Required. Zero or more Const, Dim, Enum, or Event statements declaring data members of the structure.
methodmemberdeclarations Optional. Zero or more declarations of Function, Operator, Property, or Sub procedures, which serve as method members of the structure.
End Structure Required. Terminates the Structure definition.

Remarks

The Structure statement defines a composite value type that you can customize. A structure is a generalization of the user-defined type (UDT) of previous versions of Visual Basic. For more information, see Structures.

Structures support many of the same features as classes. For example, structures can have properties and procedures, they can implement interfaces, and they can have parameterized constructors. However, there are significant differences between structures and classes in areas such as inheritance, declarations, and usage. Also, classes are reference types and structures are value types. For more information, see Structures and Classes.

You can use Structure only at namespace or module level. This means the declaration context for a structure 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.

Structures 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. You can define one structure within another. The outer structure is called the containing structure, and the inner structure is called a nested structure. However, you cannot access a nested structure's members through the containing structure. Instead, you must declare a variable of the nested structure's data type.

  • Member Declaration. You must declare every member of a structure. A structure member cannot be Protected or Protected Friend because nothing can inherit from a structure. The structure itself, however, can be Protected or Protected Friend.

    You can declare zero or more nonshared variables or nonshared, noncustom events in a structure. You cannot have only constants, properties, and procedures, even if some of them are nonshared.

  • Initialization. You cannot initialize the value of any nonshared data member of a structure as part of its declaration. You must either initialize such a data member by means of a parameterized constructor on the structure, or assign a value to the member after you have created an instance of the structure.

  • Inheritance. A structure cannot inherit from any type other than ValueType, from which all structures inherit. In particular, one structure cannot inherit from another.

    You cannot use the Inherits Statement in a structure definition, even to specify ValueType.

  • Implementation. If the structure uses the Implements Statement, you must implement every member defined by every interface you specify in interfacenames.

  • Default Property. A structure can specify at most one property as its default property, using the Default modifier. For more information, see Default.

Behavior

  • Access Level. Within a structure, you can declare each member with its own access level. All structure members default to Public access. Note that if the structure itself has a more restricted access level, this automatically restricts access to its members, even if you adjust their access levels with the access modifiers.

  • Scope. A structure is in scope throughout its containing namespace, class, structure, or module.

    The scope of every structure member is the entire structure.

  • Lifetime. A structure does not itself have a lifetime. Rather, each instance of that structure has a lifetime independent of all other instances.

    The lifetime of an instance begins when it is created by a New Operator clause. It ends when the lifetime of the variable that holds it ends.

    You cannot extend the lifetime of a structure instance. An approximation to static structure functionality is provided by a module. For more information, see Module Statement.

    Structure members have lifetimes depending on how and where they are declared. For more information, see "Lifetime" in Class Statement.

  • Qualification. Code outside a structure must qualify a member's name with the name of that structure.

    If code inside a nested structure makes an unqualified reference to a programming element, Visual Basic searches for the element first in the nested structure, then in its containing structure, and so on out to the outermost containing element. For more information, see References to Declared Elements.

  • Memory Consumption. As with all composite data types, you cannot safely calculate the total memory consumption of a structure by adding together the nominal storage allocations of its members. Furthermore, you cannot safely assume that the order of storage in memory is the same as your order of declaration. If you need to control the storage layout of a structure, you can apply the StructLayoutAttribute attribute to the Structure statement.

See also

Sub Statement

Declares the name, parameters, and code that define a Sub procedure.

Syntax

[ <attributelist> ] [ Partial ] [ accessmodifier ] [ proceduremodifiers ] [ Shared ] [ Shadows ] [ Async ]
Sub name [ (Of typeparamlist) ] [ (parameterlist) ] [ Implements implementslist | Handles eventlist ]
    [ statements ]
    [ Exit Sub ]
    [ statements ]
End Sub

Parts

  • attributelist

    Optional. See Attribute List.

  • Partial

    Optional. Indicates definition of a partial method. See Partial Methods.

  • accessmodifier

    Optional. Can be one of the following:

    See Access levels in Visual Basic.

  • proceduremodifiers

    Optional. Can be one of the following:

  • Shared

    Optional. See Shared.

  • Shadows

    Optional. See Shadows.

  • Async

    Optional. See Async.

  • name

    Required. Name of the procedure. See Declared Element Names. To create a constructor procedure for a class, set the name of a Sub procedure to the New keyword. For more information, see Object Lifetime: How Objects Are Created and Destroyed.

  • typeparamlist

    Optional. List of type parameters for a generic procedure. See Type List.

  • parameterlist

    Optional. List of local variable names representing the parameters of this procedure. See Parameter List.

  • Implements

    Optional. Indicates that this procedure implements one or more Sub procedures, each one defined in an interface implemented by this procedure's containing class or structure. See Implements Statement.

  • implementslist

    Required if Implements is supplied. List of Sub procedures being implemented.

    implementedprocedure [ , implementedprocedure ... ]

    Each implementedprocedure has the following syntax and parts:

    interface.definedname

    Part Description
    interface Required. Name of an interface implemented by this procedure's containing class or structure.
    definedname Required. Name by which the procedure is defined in interface.
  • Handles

    Optional. Indicates that this procedure can handle one or more specific events. See Handles.

  • eventlist

    Required if Handles is supplied. List of events this procedure handles.

    eventspecifier [ , eventspecifier ... ]

    Each eventspecifier has the following syntax and parts:

    eventvariable.event

    Part Description
    eventvariable Required. Object variable declared with the data type of the class or structure that raises the event.
    event Required. Name of the event this procedure handles.
  • statements

    Optional. Block of statements to run within this procedure.

  • End Sub

    Terminates the definition of this procedure.

Remarks

All executable code must be inside a procedure. Use a Sub procedure when you don't want to return a value to the calling code. Use a Function procedure when you want to return a value.

Defining a Sub Procedure

You can define a Sub procedure only at the module level. The declaration context for a sub procedure must, therefore, be a class, a structure, a module, or an interface and can't be a source file, a namespace, a procedure, or a block. For more information, see Declaration Contexts and Default Access Levels.

Sub procedures default to public access. You can adjust their access levels by using the access modifiers.

If the procedure uses the Implements keyword, the containing class or structure must have an Implements statement that immediately follows its Class or Structure statement. The Implements statement must include each interface that's specified in implementslist. However, the name by which an interface defines the Sub (in definedname) doesn't have to match the name of this procedure (in name).

Returning from a Sub Procedure

When a Sub procedure returns to the calling code, execution continues with the statement after the statement that called it.

The Exit Sub and Return statements cause an immediate exit from a Sub procedure. Any number of Exit Sub and Return statements can appear anywhere in the procedure, and you can mix Exit Sub and Return statements.

Calling a Sub Procedure

You call a Sub procedure by using the procedure name in a statement and then following that name with its argument list in parentheses. You can omit the parentheses only if you don't supply any arguments. However, your code is more readable if you always include the parentheses.

A Sub procedure and a Function procedure can have parameters and perform a series of statements. However, a Function procedure returns a value, and a Sub procedure doesn't. Therefore, you can't use a Sub procedure in an expression.

You can use the Call keyword when you call a Sub procedure, but that keyword isn't recommended for most uses. For more information, see Call Statement.

Visual Basic sometimes rearranges arithmetic expressions to increase internal efficiency. For that reason, if your argument list includes expressions that call other procedures, you shouldn't assume that those expressions will be called in a particular order.

Async Sub Procedures

By using the Async feature, you can invoke asynchronous functions without using explicit callbacks or manually splitting your code across multiple functions or lambda expressions.

If you mark a procedure with the Async modifier, you can use the Await operator in the procedure. When control reaches an Await expression in the Async procedure, control returns to the caller, and progress in the procedure is suspended until the awaited task completes. When the task is complete, execution can resume in the procedure.

Note

An Async procedure returns to the caller when either the first awaited object that’s not yet complete is encountered or the end of the Async procedure is reached, whichever occurs first.

You can also mark a Function Statement with the Async modifier. An Async function can have a return type of Task<TResult> or Task. An example later in this topic shows an Async function that has a return type of Task<TResult>.

Async Sub procedures are primarily used for event handlers, where a value can't be returned. An Async Sub procedure can't be awaited, and the caller of an Async Sub procedure can't catch exceptions that the Sub procedure throws.

An Async procedure can't declare any ByRef parameters.

For more information about Async procedures, see Asynchronous Programming with Async and Await, Control Flow in Async Programs, and Async Return Types.

See also

SyncLock Statement

Acquires an exclusive lock for a statement block before executing the block.

Syntax

SyncLock lockobject  
    [ block ]  
End SyncLock  

Parts

lockobject
Required. Expression that evaluates to an object reference.

block
Optional. Block of statements that are to execute when the lock is acquired.

End SyncLock
Terminates a SyncLock block.

Remarks

The SyncLock statement ensures that multiple threads do not execute the statement block at the same time. SyncLock prevents each thread from entering the block until no other thread is executing it.

The most common use of SyncLock is to protect data from being updated by more than one thread simultaneously. If the statements that manipulate the data must go to completion without interruption, put them inside a SyncLock block.

A statement block protected by an exclusive lock is sometimes called a critical section.

Rules

  • Branching. You cannot branch into a SyncLock block from outside the block.

  • Lock Object Value. The value of lockobject cannot be Nothing. You must create the lock object before you use it in a SyncLock statement.

    You cannot change the value of lockobject while executing a SyncLock block. The mechanism requires that the lock object remain unchanged.

  • You can't use the Await operator in a SyncLock block.

Behavior

  • Mechanism. When a thread reaches the SyncLock statement, it evaluates the lockobject expression and suspends execution until it acquires an exclusive lock on the object returned by the expression. When another thread reaches the SyncLock statement, it does not acquire a lock until the first thread executes the End SyncLock statement.

  • Protected Data. If lockobject is a Shared variable, the exclusive lock prevents a thread in any instance of the class from executing the SyncLock block while any other thread is executing it. This protects data that is shared among all the instances.

    If lockobject is an instance variable (not Shared), the lock prevents a thread running in the current instance from executing the SyncLock block at the same time as another thread in the same instance. This protects data maintained by the individual instance.

  • Acquisition and Release. A SyncLock block behaves like a Try...Finally construction in which the Try block acquires an exclusive lock on lockobject and the Finally block releases it. Because of this, the SyncLock block guarantees release of the lock, no matter how you exit the block. This is true even in the case of an unhandled exception.

  • Framework Calls. The SyncLock block acquires and releases the exclusive lock by calling the Enter and Exit methods of the Monitor class in the System.Threading namespace.

Programming Practices

The lockobject expression should always evaluate to an object that belongs exclusively to your class. You should declare a Private object variable to protect data belonging to the current instance, or a Private Shared object variable to protect data common to all instances.

You should not use the Me keyword to provide a lock object for instance data. If code external to your class has a reference to an instance of your class, it could use that reference as a lock object for a SyncLock block completely different from yours, protecting different data. In this way, your class and the other class could block each other from executing their unrelated SyncLock blocks. Similarly locking on a string can be problematic since any other code in the process using the same string will share the same lock.

You should also not use the Me.GetType method to provide a lock object for shared data. This is because GetType always returns the same Type object for a given class name. External code could call GetType on your class and obtain the same lock object you are using. This would result in the two classes blocking each other from their SyncLock blocks.

Comments

See also

Using Statement

Declares the beginning of a Using block and optionally acquires the system resources that the block controls.

Syntax

Using { resourcelist | resourceexpression }  
    [ statements ]  
End Using  

Parts

Term Definition
resourcelist Required if you do not supply resourceexpression. List of one or more system resources that this Using block controls, separated by commas.
resourceexpression Required if you do not supply resourcelist. Reference variable or expression referring to a system resource to be controlled by this Using block.
statements Optional. Block of statements that the Using block runs.
End Using Required. Terminates the definition of the Using block and disposes of all the resources that it controls.

Each resource in the resourcelist part has the following syntax and parts:

resourcename As New resourcetype [ ( [ arglist ] ) ]

-or-

resourcename As resourcetype = resourceexpression

resourcelist Parts

Term Definition
resourcename Required. Reference variable that refers to a system resource that the Using block controls.
New Required if the Using statement acquires the resource. If you have already acquired the resource, use the second syntax alternative.
resourcetype Required. The class of the resource. The class must implement the IDisposable interface.
arglist Optional. List of arguments you are passing to the constructor to create an instance of resourcetype. See Parameter List.
resourceexpression Required. Variable or expression referring to a system resource satisfying the requirements of resourcetype. If you use the second syntax alternative, you must acquire the resource before passing control to the Using statement.

Remarks

Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.

Managed resources are disposed of by the .NET Framework garbage collector (GC) without any extra coding on your part. You do not need a Using block for managed resources. However, you can still use a Using block to force the disposal of a managed resource instead of waiting for the garbage collector.

A Using block has three parts: acquisition, usage, and disposal.

  • Acquisition means creating a variable and initializing it to refer to the system resource. The Using statement can acquire one or more resources, or you can acquire exactly one resource before entering the block and supply it to the Using statement. If you supply resourceexpression, you must acquire the resource before passing control to the Using statement.

  • Usage means accessing the resources and performing actions with them. The statements between Using and End Using represent the usage of the resources.

  • Disposal means calling the Dispose method on the object in resourcename. This allows the object to cleanly terminate its resources. The End Using statement disposes of the resources under the Using block's control.

Behavior

A Using block behaves like a Try...Finally construction in which the Try block uses the resources and the Finally block disposes of them. Because of this, the Using block guarantees disposal of the resources, no matter how you exit the block. This is true even in the case of an unhandled exception, except for a StackOverflowException.

The scope of every resource variable acquired by the Using statement is limited to the Using block.

If you specify more than one system resource in the Using statement, the effect is the same as if you nested Using blocks one within another.

If resourcename is Nothing, no call to Dispose is made, and no exception is thrown.

Structured Exception Handling Within a Using Block

If you need to handle an exception that might occur within the Using block, you can add a complete Try...Finally construction to it. If you need to handle the case where the Using statement is not successful in acquiring a resource, you can test to see if resourcename is Nothing.

Structured Exception Handling Instead of a Using Block

If you need finer control over the acquisition of the resources, or you need additional code in the Finally block, you can rewrite the Using block as a Try...Finally construction.

Note

The code inside the Using block should not assign the object in resourcename to another variable. When you exit the Using block, the resource is disposed, and the other variable cannot access the resource to which it points.

See also

With...End With Statement

Executes a series of statements that repeatedly refer to a single object or structure so that the statements can use a simplified syntax when accessing members of the object or structure. When using a structure, you can only read the values of members or invoke methods, and you get an error if you try to assign values to members of a structure used in a With...End With statement.

Syntax

With objectExpression  
    [ statements ]  
End With  

Parts

Term Definition
objectExpression Required. An expression that evaluates to an object. The expression may be arbitrarily complex and is evaluated only once. The expression can evaluate to any data type, including elementary types.
statements Optional. One or more statements between With and End With that may refer to members of an object that's produced by the evaluation of objectExpression.
End With Required. Terminates the definition of the With block.

Remarks

By using With...End With, you can perform a series of statements on a specified object without specifying the name of the object multiple times. Within a With statement block, you can specify a member of the object starting with a period, as if the With statement object preceded it.

For example, to change multiple properties on a single object, place the property assignment statements inside the With...End With block, referring to the object only once instead of once for each property assignment.

If your code accesses the same object in multiple statements, you gain the following benefits by using the With statement:

  • You don't need to evaluate a complex expression multiple times or assign the result to a temporary variable to refer to its members multiple times.

  • You make your code more readable by eliminating repetitive qualifying expressions.

The data type of objectExpression can be any class or structure type or even a Visual Basic elementary type such as Integer. If objectExpression results in anything other than an object, you can only read the values of its members or invoke methods, and you get an error if you try to assign values to members of a structure used in a With...End With statement. This is the same error you would get if you invoked a method that returned a structure and immediately accessed and assigned a value to a member of the function’s result, such as GetAPoint().x = 1. The problem in both cases is that the structure exists only on the call stack, and there is no way a modified structure member in these situations can write to a location such that any other code in the program can observe the change.

The objectExpression is evaluated once, upon entry into the block. You can't reassign the objectExpression from within the With block.

Within a With block, you can access the methods and properties of only the specified object without qualifying them. You can use methods and properties of other objects, but you must qualify them with their object names.

You can place one With...End With statement within another. Nested With...End With statements may be confusing if the objects that are being referred to aren't clear from context. You must provide a fully qualified reference to an object that's in an outer With block when the object is referenced from within an inner With block.

You can't branch into a With statement block from outside the block.

Unless the block contains a loop, the statements run only once. You can nest different kinds of control structures. For more information, see Nested Control Structures.

Note

You can use the With keyword in object initializers also. For more information and examples, see Object Initializers: Named and Anonymous Types and Anonymous Types.

If you're using a With block only to initialize the properties or fields of an object that you've just instantiated, consider using an object initializer instead.

See also

 

Source/Reference


©sideway

ID: 200800016 Last Updated: 8/16/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