InternetUnicodeHTMLCSSScalable Vector Graphics (SVG)Extensible Markup Language (xml) ASP.Net TOCASP.NetMiscellaneous Feature ASP.NET Scripting Visual Basic .NET TOCVB .NET Language ReferencenaVB.Net ElementsVB.NET Operators StatementComment StatementsAssignment StatementsDeclaration StatementsContol Flow StatementsTransfer StatementsFlow StatementsMiscellaneous Statements Draft for Information Only
Content
VB.NET Procedure Block Statements
VB.NET Procedure Block StatementsThe 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 StatementDeclares 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
RemarksA 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
Behavior
Classes and ModulesThese elements have many similarities, but there are some important differences as well.
See also
Function StatementDeclares 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
RemarksAll 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 FunctionYou 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 FunctionWhen 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 FunctionYou 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 FunctionsThe 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 FunctionsAn 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 StatementDeclares a Get property procedure used to retrieve the value of a property. Syntax[ <attributelist> ] [ accessmodifier ] Get() [ statements ] End Get Parts
RemarksEvery 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
Behavior
See alsoModule StatementDeclares 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
accessmodifier See Access levels in Visual Basic.
name
statements
End Module RemarksA 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 ModulesThese elements have many similarities, but there are some important differences as well.
Rules
Behavior
See also
Operator StatementDeclares 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
Public
Overloads
Shared
Shadows
Widening
Narrowing
operatorsymbol
operand1
operand2 operand1 and operand2 have the following syntax and parts: [ ByVal ] operandname [ As operandtype ]
type
statements
returnvalue
End Operator RemarksYou 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.
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 PairsYou 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:
Data Type RestrictionsEvery 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:
Certain operators have additional data type restrictions, as follows:
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 OperatorsThe 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:
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 ConversionsA 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:
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 StatementDeclares 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
RemarksThe 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
Behavior
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 alsoStructure StatementDeclares 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
RemarksThe 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
Behavior
See also
Sub StatementDeclares 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
RemarksAll 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 ProcedureYou 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 ProcedureWhen 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 ProcedureYou 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 ProceduresBy 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 StatementAcquires an exclusive lock for a statement block before executing the block. SyntaxSyncLock lockobject [ block ] End SyncLock Parts
lockobject
block
End SyncLock RemarksThe 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
Behavior
Programming PracticesThe 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. CommentsSee alsoUsing StatementDeclares the beginning of a Using block and optionally acquires the system resources that the block controls. SyntaxUsing { resourcelist | resourceexpression } [ statements ] End Using Parts
Each resource in the resourcelist part has the following syntax and parts: resourcename As New resourcetype [ ( [ arglist ] ) ] -or- resourcename As resourcetype = resourceexpression resourcelist Parts
RemarksSometimes 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.
BehaviorA 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 BlockIf 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 BlockIf 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 alsoWith...End With StatementExecutes 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. SyntaxWith objectExpression [ statements ] End With Parts
RemarksBy 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:
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: ![]() References
![]() Latest Updated Links
![]() ![]() ![]() ![]() ![]() |
![]() Home 5 Business Management HBR 3 Information Recreation Hobbies 8 Culture Chinese 1097 English 339 Travel 18 Reference 79 Computer Hardware 254 Software Application 213 Digitization 37 Latex 52 Manim 205 KB 1 Numeric 19 Programming Web 289 Unicode 504 HTML 66 CSS 65 SVG 46 ASP.NET 270 OS 431 DeskTop 7 Python 72 Knowledge Mathematics Formulas 8 Set 1 Logic 1 Algebra 84 Number Theory 206 Trigonometry 31 Geometry 34 Calculus 67 Engineering Tables 8 Mechanical Rigid Bodies Statics 92 Dynamics 37 Fluid 5 Control Acoustics 19 Natural Sciences Matter 1 Electric 27 Biology 1 |
Copyright © 2000-2025 Sideway . All rights reserved Disclaimers last modified on 06 September 2019