Sideway
output.to from Sideway
Draft for Information Only

Content

VB.NET Procedures
 Calling a Procedure
 Returning from a Procedure
 Parameters and Arguments
 Types of Procedures
 Procedures and Structured Code
 See also
  How to: Create a Procedure
  To create a procedure that does not return a value
  To create a procedure that returns a value
  To connect your new procedure with the old, repetitive blocks of code
 Example
 See also
  Sub Procedures
 Declaration Syntax
 Parameter Declaration
  Parameters as Local Variables
 Calling Syntax
  Illustration of Declaration and Call
 See also
  How to: Call a Procedure that Does Not Return a Value
  To call a Sub procedure
 See also
  How to: Call an Event Handler in Visual Basic
  To call an event handler using Handles and WithEvents
  To call an event handler using AddHandler
 See also
  Function Procedures
 Declaration Syntax
  Data Type
 Returning Values
 Calling Syntax
  Illustration of Declaration and Call
 See also
  How to: Create a Procedure that Returns a Value
  To create a procedure that returns a value
 See also
  How to: Return a Value from a Procedure
  To return a value using the Return statement
  To return a value using Exit Function or End Function
 See also
  How to: Call a Procedure That Returns a Value
  To call a Function procedure within an expression
  To call a Function procedure in an assignment statement
 Example
 See also
  Property Procedures
 Declaration Syntax
  Data Type
  Access Level
 Parameter Declaration
 Property Value
 Calling Syntax
  Illustration of Declaration and Call
 See also
  Auto-Implemented Properties
 Backing Field
 Initializing an Auto-Implemented Property
 Property Definitions That Require Standard Syntax
 Expanding an Auto-Implemented Property
 See also
  Differences Between Properties and Variables in Visual Basic
 Variables
 Properties
 Differences
 See also
  How to: Create a Property
  To create a property
  To create a Get procedure that retrieves a property value
  To create a Set procedure that writes a property's value
 Example
 See also
  How to: Declare a Property with Mixed Access Levels
  To declare a property with mixed access levels
 See also
  How to: Call a Property Procedure
  To call a property's Get procedure
  To call a property's Set procedure
 See also
  How to: Declare and Call a Default Property in Visual Basic
  To declare a default property
  To call a default property
 Example
 Example
 Robust Programming
 See also
  How to: Put a Value in a Property
  To store a value in a property
 See also
  How to: Get a Value from a Property
  To retrieve a value from a property
 See also
  Operator Procedures
 When to Define Operator Procedures
 Types of Operator Procedure
 Declaration Syntax
  Data Type
 Calling Syntax
  Illustration of Declaration and Call
 See also
  How to: Define an Operator
 Example
 See also
  How to: Define a Conversion Operator
 Example
 See also
  How to: Call an Operator Procedure
  To call an operator procedure
  To call a conversion operator procedure
 Example
 Compiling the Code
 See also
  How to: Use a Class that Defines Operators
 Example
 Compiling the Code
 See also
  Source/Reference

VB.NET Procedures

A procedure is a block of Visual Basic statements enclosed by a declaration statement (Function, Sub, Operator, Get, Set) and a matching End declaration. All executable statements in Visual Basic must be within some procedure.

Calling a Procedure

You invoke a procedure from some other place in the code. This is known as a procedure call. When the procedure is finished running, it returns control to the code that invoked it, which is known as the calling code. The calling code is a statement, or an expression within a statement, that specifies the procedure by name and transfers control to it.

Returning from a Procedure

A procedure returns control to the calling code when it has finished running. To do this, it can use a Return Statement, the appropriate Exit Statement statement for the procedure, or the procedure's End <keyword> Statement statement. Control then passes to the calling code following the point of the procedure call.

  • With a Return statement, control returns immediately to the calling code. Statements following the Return statement do not run. You can have more than one Return statement in the same procedure.

  • With an Exit Sub or Exit Function statement, control returns immediately to the calling code. Statements following the Exit statement do not run. You can have more than one Exit statement in the same procedure, and you can mix Return and Exit statements in the same procedure.

  • If a procedure has no Return or Exit statements, it concludes with an End Sub or End Function, End Get, or End Set statement following the last statement of the procedure body. The End statement returns control immediately to the calling code. You can have only one End statement in a procedure.

Parameters and Arguments

In most cases, a procedure needs to operate on different data each time you call it. You can pass this information to the procedure as part of the procedure call. The procedure defines zero or more parameters, each of which represents a value it expects you to pass to it. Corresponding to each parameter in the procedure definition is an argument in the procedure call. An argument represents the value you pass to the corresponding parameter in a given procedure call.

Types of Procedures

Visual Basic uses several types of procedures:

  • Sub Procedures perform actions but do not return a value to the calling code.

  • Event-handling procedures are Sub procedures that execute in response to an event raised by user action or by an occurrence in a program.

  • Function Procedures return a value to the calling code. They can perform other actions before returning.

    Some functions written in C# return a reference return value. Function callers can modify the return value, and this modification is reflected in the state of the called object. Starting with Visual Basic 2017, Visual Basic code can consume reference return values, although it cannot return a value by reference. For more information, see Reference return values.

  • Property Procedures return and assign values of properties on objects or modules.

  • Operator Procedures define the behavior of a standard operator when one or both of the operands is a newly-defined class or structure.

  • Generic Procedures in Visual Basic define one or more type parameters in addition to their normal parameters, so the calling code can pass specific data types each time it makes a call.

Procedures and Structured Code

Every line of executable code in your application must be inside some procedure, such as Main, calculate, or Button1_Click. If you subdivide large procedures into smaller ones, your application is more readable.

Procedures are useful for performing repeated or shared tasks, such as frequently used calculations, text and control manipulation, and database operations. You can call a procedure from many different places in your code, so you can use procedures as building blocks for your application.

Structuring your code with procedures gives you the following benefits:

  • Procedures allow you to break your programs into discrete logical units. You can debug separate units more easily than you can debug an entire program without procedures.

  • After you develop procedures for use in one program, you can use them in other programs, often with little or no modification. This helps you avoid code duplication.

See also

How to: Create a Procedure

You enclose a procedure between a starting declaration statement (Sub or Function) and an ending declaration statement (End Sub or End Function). All the procedure's code lies between these statements.

A procedure cannot contain another procedure, so its starting and ending statements must be outside any other procedure.

If you have code that performs the same task in different places, you can write the task once as a procedure and then call it from different places in your code.

To create a procedure that does not return a value

  1. Outside any other procedure, use a Sub statement, followed by an End Sub statement.

  2. In the Sub statement, follow the Sub keyword with the name of the procedure, then the parameter list in parentheses.

  3. Place the procedure's code statements between the Sub and End Sub statements.

To create a procedure that returns a value

  1. Outside any other procedure, use a Function statement, followed by an End Function statement.

  2. In the Function statement, follow the Function keyword with the name of the procedure, then the parameter list in parentheses, and then an As clause specifying the data type of the return value.

  3. Place the procedure's code statements between the Function and End Function statements.

  4. Use a Return statement to return the value to the calling code.

To connect your new procedure with the old, repetitive blocks of code

  1. Make sure you define the new procedure in a place where the old code has access to it.

  2. In your old, repetitive code block, replace the statements that perform the repetitive task with a single statement that calls the Sub or Function procedure.

  3. If your procedure is a Function that returns a value, ensure that your calling statement performs an action with the returned value, such as storing it in a variable, or else the value will be lost.

Example

The following Function procedure calculates the longest side, or hypotenuse, of a right triangle, given the values for the other two sides.

VB
Function hypotenuse(ByVal side1 As Single, ByVal side2 As Single) As Single
    Return Math.Sqrt((side1 ^ 2) + (side2 ^ 2))
End Function

See also

Sub Procedures

A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End Sub statements. The Sub procedure performs a task and then returns control to the calling code, but it does not return a value to the calling code.

Each time the procedure is called, its statements are executed, starting with the first executable statement after the Sub statement and ending with the first End Sub, Exit Sub, or Return statement encountered.

You can define a Sub procedure in modules, classes, and structures. By default, it is Public, which means you can call it from anywhere in your application that has access to the module, class, or structure in which you defined it. The term, method, describes a Sub or Function procedure that is accessed from outside its defining module, class, or structure. For more information, see Procedures.

A Sub procedure can take arguments, such as constants, variables, or expressions, which are passed to it by the calling code.

Declaration Syntax

The syntax for declaring a Sub procedure is as follows:

[ modifiers ] Sub subname [( parameterlist )]

' Statements of the Sub procedure.

End Sub

The modifiers can specify access level and information about overloading, overriding, sharing, and shadowing. For more information, see Sub Statement.

Parameter Declaration

You declare each procedure parameter similarly to how you declare a variable, specifying the parameter name and data type. You can also specify the passing mechanism, and whether the parameter is optional or a parameter array.

The syntax for each parameter in the parameter list is as follows:

[Optional] [ByVal | ByRef] [ParamArray] parametername As datatype

If the parameter is optional, you must also supply a default value as part of its declaration. The syntax for specifying a default value is as follows:

Optional [ByVal | ByRef] parametername As datatype = defaultvalue

Parameters as Local Variables

When control passes to the procedure, each parameter is treated as a local variable. This means that its lifetime is the same as that of the procedure, and its scope is the whole procedure.

Calling Syntax

You invoke a Sub procedure explicitly with a stand-alone calling statement. You cannot call it by using its name in an expression. You must provide values for all arguments that are not optional, and you must enclose the argument list in parentheses. If no arguments are supplied, you can optionally omit the parentheses. The use of the Call keyword is optional but not recommended.

The syntax for a call to a Sub procedure is as follows:

[Call] subname [( argumentlist )]

You can call a Sub method from outside the class that defines it. First, you have to use the New keyword to create an instance of the class, or call a method that returns an instance of the class. For more information, see New Operator. Then, you can use the following syntax to call the Sub method on the instance object:

Object.methodname[(argumentlist)]

Illustration of Declaration and Call

The following Sub procedure tells the computer operator which task the application is about to perform, and also displays a time stamp. Instead of duplicating this code at the start of every task, the application just calls tellOperator from various locations. Each call passes a string in the task argument that identifies the task being started.

VB
Sub tellOperator(ByVal task As String)
    Dim stamp As Date
    stamp = TimeOfDay()
    MsgBox("Starting " & task & " at " & CStr(stamp))
End Sub

The following example shows a typical call to tellOperator.

VB
tellOperator("file update")

See also

How to: Call a Procedure that Does Not Return a Value

A Sub procedure does not return a value to the calling code. You call it explicitly with a stand-alone calling statement. You cannot call it by simply using its name within an expression.

To call a Sub procedure

  1. Specify the name of the Sub procedure.

  2. Follow the procedure name with parentheses to enclose the argument list. If there are no arguments, you can optionally omit the parentheses. However, using the parentheses makes your code easier to read.

  3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the arguments in the same order that the Sub procedure defines the corresponding parameters.

    The following example calls the Visual Basic AppActivate function to activate an application window. AppActivate takes the window title as its sole argument. It does not return a value to the calling code. If a Notepad process is not running, the example throws an ArgumentException. The Shell procedure assumes the applications are in the paths specified.

    VB
    Dim notepadID As Integer
    ' Activate a running Notepad process.
    AppActivate("Untitled - Notepad")
    ' AppActivate can also use the return value of the Shell function.
    ' Shell runs a new instance of Notepad.
    notepadID = Shell("C:\WINNT\NOTEPAD.EXE", AppWinStyle.NormalFocus)
    ' Activate the new instance of Notepad.  
    AppActivate(notepadID)
    

See also

How to: Call an Event Handler in Visual Basic

An event is an action or occurrence — such as a mouse click or a credit limit exceeded — that is recognized by some program component, and for which you can write code to respond. An event handler is the code you write to respond to an event.

An event handler in Visual Basic is a Sub procedure. However, you do not normally call it the same way as other Sub procedures. Instead, you identify the procedure as a handler for the event. You can do this either with a Handles clause and a WithEvents variable, or with an AddHandler Statement. Using a Handles clause is the default way to declare an event handler in Visual Basic. This is the way the event handlers are written by the designers when you program in the integrated development environment (IDE). The AddHandler statement is suitable for raising events dynamically at run time.

When the event occurs, Visual Basic automatically calls the event handler procedure. Any code that has access to the event can cause it to occur by executing a RaiseEvent Statement.

You can associate more than one event handler with the same event. In some cases you can dissociate a handler from an event. For more information, see Events.

To call an event handler using Handles and WithEvents

  1. Make sure the event is declared with an Event Statement.

  2. Declare an object variable at module or class level, using the WithEvents keyword. The As clause for this variable must specify the class that raises the event.

  3. In the declaration of the event-handling Sub procedure, add a Handles clause that specifies the WithEvents variable and the event name.

  4. When the event occurs, Visual Basic automatically calls the Sub procedure. Your code can use a RaiseEvent statement to make the event occur.

    The following example defines an event and a WithEvents variable that refers to the class that raises the event. The event-handling Sub procedure uses a Handles clause to specify the class and event it handles.

    VB
    Public Class raisesEvent
        Public Event somethingHappened()
        Dim WithEvents happenObj As New raisesEvent
        Public Sub processHappen() Handles happenObj.somethingHappened
            ' Insert code to handle somethingHappened event.
        End Sub
    End Class
    

To call an event handler using AddHandler

  1. Make sure the event is declared with an Event statement.

  2. Execute an AddHandler Statement to dynamically connect the event-handling Sub procedure with the event.

  3. When the event occurs, Visual Basic automatically calls the Sub procedure. Your code can use a RaiseEvent statement to make the event occur.

    The following example defines a Sub procedure to handle the Closing event of a form. It then uses the AddHandler Statement to associate the catchClose procedure as an event handler for Closing.

    VB
  1. ' Place these procedures inside a Form class definition.
    Private Sub catchClose(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
        ' Insert code to deal with impending closure of this form.
    End Sub
    Public Sub formOpened()
        AddHandler Me.Closing, AddressOf catchClose
    End Sub
    

    You can dissociate an event handler from an event by executing the RemoveHandler Statement.

See also

Function Procedures

A Function procedure is a series of Visual Basic statements enclosed by the Function and End Function statements. The Function procedure performs a task and then returns control to the calling code. When it returns control, it also returns a value to the calling code.

Each time the procedure is called, its statements run, starting with the first executable statement after the Function statement and ending with the first End Function, Exit Function, or Return statement encountered.

You can define a Function procedure in a module, class, or structure. It is Public by default, which means you can call it from anywhere in your application that has access to the module, class, or structure in which you defined it.

A Function procedure can take arguments, such as constants, variables, or expressions, which are passed to it by the calling code.

Declaration Syntax

The syntax for declaring a Function procedure is as follows:

VB
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType  
    [Statements]  
End Function  

The modifiers can specify access level and information regarding overloading, overriding, sharing, and shadowing. For more information, see Function Statement.

You declare each parameter the same way you do for Sub Procedures.

Data Type

Every Function procedure has a data type, just as every variable does. This data type is specified by the As clause in the Function statement, and it determines the data type of the value the function returns to the calling code. The following sample declarations illustrate this.

VB
Function yesterday() As Date  
End Function  
  
Function findSqrt(ByVal radicand As Single) As Single  
End Function  

For more information, see "Parts" in Function Statement.

Returning Values

The value a Function procedure sends back to the calling code is called its return value. The procedure returns this value in one of two ways:

  • It uses the Return statement to specify the return value, and returns control immediately to the calling program. The following example illustrates this.
VB
Function FunctionName [(ParameterList)] As ReturnType  
    ' The following statement immediately transfers control back  
    ' to the calling code and returns the value of Expression.  
    Return Expression  
End Function  
  • It assigns a value to its own function name in one or more statements of the procedure. Control does not return to the calling program until an Exit Function or End Function statement is executed. The following example illustrates this.
VB
Function FunctionName [(ParameterList)] As ReturnType  
    ' The following statement does not transfer control back to the calling code.  
    FunctionName = Expression  
    ' When control returns to the calling code, Expression is the return value.  
End Function  

The advantage of assigning the return value to the function name is that control does not return from the procedure until it encounters an Exit Function or End Function statement. This allows you to assign a preliminary value and adjust it later if necessary.

For more information about returning values, see Function Statement. For information about returning arrays, see Arrays.

Calling Syntax

You invoke a Function procedure by including its name and arguments either on the right side of an assignment statement or in an expression. You must provide values for all arguments that are not optional, and you must enclose the argument list in parentheses. If no arguments are supplied, you can optionally omit the parentheses.

The syntax for a call to a Function procedure is as follows:

lvalue = functionname [( argumentlist )]

If (( functionname [( argumentlist )] / 3) <= expression ) Then

When you call a Function procedure, you do not have to use its return value. If you do not, all the actions of the function are performed, but the return value is ignored. MsgBox is often called in this manner.

Illustration of Declaration and Call

The following Function procedure calculates the longest side, or hypotenuse, of a right triangle, given the values for the other two sides.

VB
Function hypotenuse(ByVal side1 As Single, ByVal side2 As Single) As Single
    Return Math.Sqrt((side1 ^ 2) + (side2 ^ 2))
End Function

The following example shows a typical call to hypotenuse.

VB
Dim testLength, testHypotenuse As Single
testHypotenuse = hypotenuse(testLength, 10.7)

See also

How to: Create a Procedure that Returns a Value

You use a Function procedure to return a value to the calling code.

To create a procedure that returns a value

  1. Outside any other procedure, use a Function statement, followed by an End Function statement.

  2. In the Function statement, follow the Function keyword with the name of the procedure, and then the parameter list in parentheses.

  3. Follow the parentheses with an As clause to specify the data type of the returned value.

  4. Place the procedure's code statements between the Function and End Function statements.

  5. Use a Return statement to return the value to the calling code.

    The following Function procedure calculates the longest side, or hypotenuse, of a right triangle, given the values for the other two sides.

    VB
    Function hypotenuse(ByVal side1 As Single, ByVal side2 As Single) As Single
        Return Math.Sqrt((side1 ^ 2) + (side2 ^ 2))
    End Function
    

    The following example shows a typical call to hypotenuse.

    VB
    Dim testLength, testHypotenuse As Single
    testHypotenuse = hypotenuse(testLength, 10.7)
    

See also

How to: Return a Value from a Procedure

A Function procedure returns a value to the calling code either by executing a Return statement or by encountering an Exit Function or End Function statement.

To return a value using the Return statement

  1. Put a Return statement at the point where the procedure's task is completed.

  2. Follow the Return keyword with an expression that yields the value you want to return to the calling code.

  3. You can have more than one Return statement in the same procedure.

    The following Function procedure calculates the longest side, or hypotenuse, of a right triangle, and returns it to the calling code.

    VB
    Function hypotenuse(ByVal side1 As Single, ByVal side2 As Single) As Single
        Return Math.Sqrt((side1 ^ 2) + (side2 ^ 2))
    End Function
    

    The following example shows a typical call to hypotenuse, which stores the returned value.

    VB
    Dim testLength, testHypotenuse As Single
    testHypotenuse = hypotenuse(testLength, 10.7)
    

To return a value using Exit Function or End Function

  1. In at least one place in the Function procedure, assign a value to the procedure's name.

  2. When you execute an Exit Function or End Function statement, Visual Basic returns the value most recently assigned to the procedure's name.

  3. You can have more than one Exit Function statement in the same procedure, and you can mix Return and Exit Function statements in the same procedure.

  4. You can have only one End Function statement in a Function procedure.

    For more information and an example, see "Return Value" in Function Statement.

See also

How to: Call a Procedure That Returns a Value

A Function procedure returns a value to the calling code. You call it by including its name and arguments either on the right side of an assignment statement or in an expression.

To call a Function procedure within an expression

  1. Use the Function procedure name the same way you would use a variable. You can use a Function procedure call anywhere you can use a variable or constant in an expression.

  2. Follow the procedure name with parentheses to enclose the argument list. If there are no arguments, you can optionally omit the parentheses. However, using the parentheses makes your code easier to read.

  3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the arguments in the same order that the Function procedure defines the corresponding parameters.

    Alternatively, you can pass one or more arguments by name. For more information, see Passing Arguments by Position and by Name.

  4. The value returned from the procedure participates in the expression just as the value of a variable or constant would.

To call a Function procedure in an assignment statement

  1. Use the Function procedure name following the equal (=) sign in the assignment statement.

  2. Follow the procedure name with parentheses to enclose the argument list. If there are no arguments, you can optionally omit the parentheses. However, using the parentheses makes your code easier to read.

  3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the arguments in the same order that the Function procedure defines the corresponding parameters, unless you are passing them by name.

  4. The value returned from the procedure is stored in the variable or property on the left side of the assignment statement.

Example

The following example calls the Visual Basic Environ to retrieve the value of an operating system environment variable. The first line calls Environ within an expression, and the second line calls it in an assignment statement. Environ takes the variable name as its sole argument. It returns the variable's value to the calling code.

VB
MsgBox("Value of PATH is " & Environ("PATH"))
Dim currentPath As String = Environ("PATH")

See also

Property Procedures

A property procedure is a series of Visual Basic statements that manipulate a custom property on a module, class, or structure. Property procedures are also known as property accessors.

Visual Basic provides for the following property procedures:

  • A Get procedure returns the value of a property. It is called when you access the property in an expression.

  • A Set procedure sets a property to a value, including an object reference. It is called when you assign a value to the property.

You usually define property procedures in pairs, using the Get and Set statements, but you can define either procedure alone if the property is read-only (Get Statement) or write-only (Set Statement).

You can omit the Get and Set procedure when using an auto-implemented property. For more information, see Auto-Implemented Properties.

You can define properties in classes, structures, and modules. Properties are Public by default, which means you can call them from anywhere in your application that can access the property's container.

For a comparison of properties and variables, see Differences Between Properties and Variables in Visual Basic.

Declaration Syntax

A property itself is defined by a block of code enclosed within the Property Statement and the End Property statement. Inside this block, each property procedure appears as an internal block enclosed within a declaration statement (Get or Set) and the matching End declaration.

The syntax for declaring a property and its procedures is as follows:

[Default] [Modifiers] Property PropertyName[(ParameterList)] [As DataType]  
    [AccessLevel] Get  
        ' Statements of the Get procedure.  
        ' The following statement returns an expression as the property's value.  
        Return Expression  
    End Get  
    [AccessLevel] Set[(ByVal NewValue As DataType)]  
        ' Statements of the Set procedure.  
        ' The following statement assigns newvalue as the property's value.  
        LValue = NewValue  
    End Set  
End Property  
- or -  
[Default] [Modifiers] Property PropertyName [(ParameterList)] [As DataType]  

The Modifiers can specify access level and information regarding overloading, overriding, sharing, and shadowing, as well as whether the property is read-only or write-only. The AccessLevel on the Get or Set procedure can be any level that is more restrictive than the access level specified for the property itself. For more information, see Property Statement.

Data Type

A property's data type and principal access level are defined in the Property statement, not in the property procedures. A property can have only one data type. For example, you cannot define a property to store a Decimal value but retrieve a Double value.

Access Level

However, you can define a principal access level for a property and further restrict the access level in one of its property procedures. For example, you can define a Public property and then define a Private Set procedure. The Get procedure remains Public. You can change the access level in only one of a property's procedures, and you can only make it more restrictive than the principal access level. For more information, see How to: Declare a Property with Mixed Access Levels.

Parameter Declaration

You declare each parameter the same way you do for Sub Procedures, except that the passing mechanism must be ByVal.

The syntax for each parameter in the parameter list is as follows:

[Optional] ByVal [ParamArray] parametername As datatype

If the parameter is optional, you must also supply a default value as part of its declaration. The syntax for specifying a default value is as follows:

Optional ByVal parametername As datatype = defaultvalue

Property Value

In a Get procedure, the return value is supplied to the calling expression as the value of the property.

In a Set procedure, the new property value is passed to the parameter of the Set statement. If you explicitly declare a parameter, you must declare it with the same data type as the property. If you do not declare a parameter, the compiler uses the implicit parameter Value to represent the new value to be assigned to the property.

Calling Syntax

You invoke a property procedure implicitly by making reference to the property. You use the name of the property the same way you would use the name of a variable, except that you must provide values for all arguments that are not optional, and you must enclose the argument list in parentheses. If no arguments are supplied, you can optionally omit the parentheses.

The syntax for an implicit call to a Set procedure is as follows:

propertyname[(argumentlist)] = expression

The syntax for an implicit call to a Get procedure is as follows:

lvalue = propertyname[(argumentlist)]

Do While (propertyname[(argumentlist)] > expression)

Illustration of Declaration and Call

The following property stores a full name as two constituent names, the first name and the last name. When the calling code reads fullName, the Get procedure combines the two constituent names and returns the full name. When the calling code assigns a new full name, the Set procedure attempts to break it into two constituent names. If it does not find a space, it stores it all as the first name.

VB
Dim firstName, lastName As String
Property fullName() As String
    Get
      If lastName = "" Then
          Return firstName
      Else
          Return firstName & " " & lastName
      End If

    End Get
    Set(ByVal Value As String)
        Dim space As Integer = Value.IndexOf(" ")
        If space < 0 Then
            firstName = Value
            lastName = ""
        Else
            firstName = Value.Substring(0, space)
            lastName = Value.Substring(space + 1)
        End If
    End Set
End Property

The following example shows typical calls to the property procedures of fullName.

VB
fullName = "MyFirstName MyLastName"
MsgBox(fullName)

See also

Auto-Implemented Properties

Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property. When you write code for an auto-implemented property, the Visual Basic compiler automatically creates a private field to store the property variable in addition to creating the associated Get and Set procedures.

With auto-implemented properties, a property, including a default value, can be declared in a single line. The following example shows three property declarations.

VB
Public Property Name As String
Public Property Owner As String = "DefaultName"
Public Property Items As New List(Of String) From {"M", "T", "W"}
Public Property ID As New Guid()

An auto-implemented property is equivalent to a property for which the property value is stored in a private field. The following code example shows an auto-implemented property.

VB
Property Prop2 As String = "Empty"

The following code example shows the equivalent code for the previous auto-implemented property example.

VB
Private _Prop2 As String = "Empty"
Property Prop2 As String
    Get
        Return _Prop2
    End Get
    Set(ByVal value As String)
        _Prop2 = value
    End Set
End Property

The following code show implementing readonly properties:

VB
Class Customer  
   Public ReadOnly Property Tags As New List(Of String)  
   Public ReadOnly Property Name As String = ""  
   Public ReadOnly Property File As String  
  
   Sub New(file As String)  
      Me.File = file  
   End Sub  
End Class  

You can assign to the property with initialization expressions as shown in the example, or you can assign to the properties in the containing type’s constructor. You can assign to the backing fields of readonly properties at any time.

Backing Field

When you declare an auto-implemented property, Visual Basic automatically creates a hidden private field called the backing field to contain the property value. The backing field name is the auto-implemented property name preceded by an underscore (_). For example, if you declare an auto-implemented property named ID, the backing field is named _ID. If you include a member of your class that is also named _ID, you produce a naming conflict and Visual Basic reports a compiler error.

The backing field also has the following characteristics:

  • The access modifier for the backing field is always Private, even when the property itself has a different access level, such as Public.

  • If the property is marked as Shared, the backing field also is shared.

  • Attributes specified for the property do not apply to the backing field.

  • The backing field can be accessed from code within the class and from debugging tools such as the Watch window. However, the backing field does not show in an IntelliSense word completion list.

Initializing an Auto-Implemented Property

Any expression that can be used to initialize a field is valid for initializing an auto-implemented property. When you initialize an auto-implemented property, the expression is evaluated and passed to the Set procedure for the property. The following code examples show some auto-implemented properties that include initial values.

VB
Property FirstName As String = "James"
Property PartNo As Integer = 44302
Property Orders As New List(Of Order)(500)

You cannot initialize an auto-implemented property that is a member of an Interface, or one that is marked MustOverride.

When you declare an auto-implemented property as a member of a Structure, you can only initialize the auto-implemented property if it is marked as Shared.

When you declare an auto-implemented property as an array, you cannot specify explicit array bounds. However, you can supply a value by using an array initializer, as shown in the following examples.

VB
Property Grades As Integer() = {90, 73}
Property Temperatures As Integer() = New Integer() {68, 54, 71}

Property Definitions That Require Standard Syntax

Auto-implemented properties are convenient and support many programming scenarios. However, there are situations in which you cannot use an auto-implemented property and must instead use standard, or expanded, property syntax.

You have to use expanded property-definition syntax if you want to do any one of the following:

  • Add code to the Get or Set procedure of a property, such as code to validate incoming values in the Set procedure. For example, you might want to verify that a string that represents a telephone number contains the required number of numerals before setting the property value.

  • Specify different accessibility for the Get and Set procedure. For example, you might want to make the Set procedure Private and the Get procedure Public.

  • Create properties that are WriteOnly.

  • Use parameterized properties (including Default properties). You must declare an expanded property in order to specify a parameter for the property, or to specify additional parameters for the Set procedure.

  • Place an attribute on the backing field, or change the access level of the backing field.

  • Provide XML comments for the backing field.

Expanding an Auto-Implemented Property

If you have to convert an auto-implemented property to an expanded property that contains a Get or Set procedure, the Visual Basic Code Editor can automatically generate the Get and Set procedures and End Property statement for the property. The code is generated if you put the cursor on a blank line following the Property statement, type a G (for Get) or an S (for Set) and press ENTER. The Visual Basic Code Editor automatically generates the Get or Set procedure for read-only and write-only properties when you press ENTER at the end of a Property statement.

See also

Differences Between Properties and Variables in Visual Basic

Variables and properties both represent values that you can access. However, there are differences in storage and implementation.

Variables

A variable corresponds directly to a memory location. You define a variable with a single declaration statement. A variable can be a local variable, defined inside a procedure and available only within that procedure, or it can be a member variable, defined in a module, class, or structure but not inside any procedure. A member variable is also called a field.

Properties

A property is a data element defined on a module, class, or structure. You define a property with a code block between the Property and End Property statements. The code block contains a Get procedure, a Set procedure, or both. These procedures are called property procedures or property accessors. In addition to retrieving or storing the property's value, they can also perform custom actions, such as updating an access counter.

Differences

The following table shows some important differences between variables and properties.

Point of difference Variable Property
Declaration Single declaration statement Series of statements in a code block
Implementation Single storage location Executable code (property procedures)
Storage Directly associated with variable's value Typically has internal storage not available outside the property's containing class or module

Property's value might or might not exist as a stored element 1
Executable code None Must have at least one procedure
Read and write access Read/write or read-only Read/write, read-only, or write-only
Custom actions (in addition to accepting or returning value) Not possible Can be performed as part of setting or retrieving property value

1 Unlike a variable, the value of a property might not correspond directly to a single item of storage. The storage might be split into pieces for convenience or security, or the value might be stored in an encrypted form. In these cases the Get procedure would assemble the pieces or decrypt the stored value, and the Set procedure would encrypt the new value or split it into the constituent storage. A property value might be ephemeral, like time of day, in which case the Get procedure would calculate it on the fly each time you access the property.

See also

How to: Create a Property

You enclose a property definition between a Property statement and an End Property statement. Within this definition you define a Get procedure, a Set procedure, or both. All the property's code lies within these procedures.

The Get procedure retrieves the property's value, and the Set procedure stores a value. If you want the property to have read/write access, you must define both procedures. For a read-only property, you define only Get, and for a write-only property, you define only Set.

To create a property

  1. Outside any property or procedure, use a Property Statement, followed by an End Property statement.

  2. If the property takes parameters, follow the Property keyword with the name of the procedure, then the parameter list in parentheses.

  3. Follow the parentheses with an As clause to specify the data type of the property's value. You must specify the data type even for a write-only property.

  4. Add Get and Set procedures, as appropriate. See the following directions.

To create a Get procedure that retrieves a property value

  1. Between the Property and End Property statements, write a Get Statement, followed by an End Get statement. You do not need to define any parameters for the Get procedure.

  2. Place the code statements to retrieve the property's value between the Get and End Get statements. This code can include other calculations and data manipulations in addition to generating and returning the property's value.

  3. Use a Return statement to return the property's value to the calling code.

You must write a Get procedure for a read-write property and for a read-only property. You must not define a Get procedure for a write-only property.

To create a Set procedure that writes a property's value

  1. Between the Property and End Property statements, write a Set Statement, followed by an End Set statement.

  2. In the Set statement, follow the Set keyword with a parameter list in parentheses. This parameter list must include at least a value parameter for the value passed by the calling code. The default name for this value parameter is Value, but you can use a different name if appropriate. The value parameter must have the same data type as the property itself.

  3. Place the code statements to store a value in the property between the Set and End Set statements. This code can include other calculations and data manipulations in addition to validating and storing the property's value.

  4. Use the value parameter to accept the value supplied by the calling code. You can either store this value directly in an assignment statement, or use it in an expression to calculate the internal value to be stored.

You must write a Set procedure for a read-write property and for a write-only property. You must not define a Set procedure for a read-only property.

Example

The following example creates a read/write property that stores a full name as two constituent names, the first name and the last name. When the calling code reads fullName, the Get procedure combines the two constituent names and returns the full name. When the calling code assigns a new full name, the Set procedure attempts to break it into two constituent names. If it does not find a space, it stores it all as the first name.

VB
Dim firstName, lastName As String
Property fullName() As String
    Get
      If lastName = "" Then
          Return firstName
      Else
          Return firstName & " " & lastName
      End If

    End Get
    Set(ByVal Value As String)
        Dim space As Integer = Value.IndexOf(" ")
        If space < 0 Then
            firstName = Value
            lastName = ""
        Else
            firstName = Value.Substring(0, space)
            lastName = Value.Substring(space + 1)
        End If
    End Set
End Property

The following example shows typical calls to the property procedures of fullName. The first call sets the property value and the second call retrieves it.

VB
fullName = "MyFirstName MyLastName"
MsgBox(fullName)

See also

How to: Declare a Property with Mixed Access Levels

If you want the Get and Set procedures on a property to have different access levels, you can use the more permissive level in the Property statement and the more restrictive level in either the Get or Set statement. You use mixed access levels on a property when you want certain parts of the code to be able to get the property's value, and certain other parts of the code to be able to change the value.

For more information on access levels, see Access levels in Visual Basic.

To declare a property with mixed access levels

  1. Declare the property in the normal way, and specify the less restrictive access level (such as Public) in the Property statement.

  2. Declare either the Get or the Set procedure specifying the more restrictive access level (such as Friend).

  3. Do not specify an access level on the other property procedure. It assumes the access level declared in the Property statement. You can restrict access on only one of the property procedures.

    VB
    Public Class employee
        Private salaryValue As Double
        Protected Property salary() As Double
            Get
                Return salaryValue
            End Get
            Private Set(ByVal value As Double)
                salaryValue = value
            End Set
        End Property
    End Class
    

    In the preceding example, the Get procedure has the same Protected access as the property itself, while the Set procedure has Private access. A class derived from employee can read the salary value, but only the employee class can set it.

See also

How to: Call a Property Procedure

You call a property procedure by storing a value in the property or retrieving its value. You access a property the same way you access a variable.

The property's Set procedure stores a value, and its Get procedure retrieves the value. However, you do not explicitly call these procedures by name. You use the property in an assignment statement or an expression, just as you would store or retrieve the value of a variable. Visual Basic makes the calls to the property's procedures.

To call a property's Get procedure

  1. Use the property name in an expression the same way you would use a variable name. You can use a property anywhere you can use a variable or a constant.

    -or-

    Use the property name following the equal (=) sign in an assignment statement.

    The following example reads the value of the Now property, implicitly calling its Get procedure.

    VB
    Dim ThisMoment As Date
    ' The following statement calls the Get procedure of the Visual Basic Now property.
    ThisMoment = Now
    
  2. If the property takes arguments, follow the property name with parentheses to enclose the argument list. If there are no arguments, you can optionally omit the parentheses.

  3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the arguments in the same order that the property defines the corresponding parameters.

The value of the property participates in the expression just as a variable or constant would, or it is stored in the variable or property on the left side of the assignment statement.

To call a property's Set procedure

  1. Use the property name on the left side of an assignment statement.

    The following example sets the value of the TimeOfDay property, implicitly calling the Set procedure.

    VB
    ' The following statement calls the Set procedure of the Visual Basic TimeOfDay property.
    TimeOfDay = #12:00:00 PM#
    
  2. If the property takes arguments, follow the property name with parentheses to enclose the argument list. If there are no arguments, you can optionally omit the parentheses.

  3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the arguments in the same order that the property defines the corresponding parameters.

The value generated on the right side of the assignment statement is stored in the property.

See also

How to: Declare and Call a Default Property in Visual Basic

A default property is a class or structure property that your code can access without specifying it. When calling code names a class or structure but not a property, and the context allows access to a property, Visual Basic resolves the access to that class or structure's default property if one exists.

A class or structure can have at most one default property. However, you can overload a default property and have more than one version of it.

For more information, see Default.

To declare a default property

  1. Declare the property in the normal way. Do not specify the Shared or Private keyword.

  2. Include the Default keyword in the property declaration.

  3. Specify at least one parameter for the property. You cannot define a default property that does not take at least one argument.

    VB
    Default Property myProperty(ByVal index As Integer) As String
    

To call a default property

  1. Declare a variable of the containing class or structure type.

    VB
    Dim x As New class1(3)
    
  2. Use the variable name alone in an expression where you would normally include the property name.

    VB
    MsgBox(x)
    
  3. Follow the variable name with an argument list in parentheses. A default property must take at least one argument.

    VB
    MsgBox(x(1))
    
  4. To retrieve the default property value, use the variable name, with an argument list, in an expression or following the equal (=) sign in an assignment statement.

    VB
    MsgBox(x(1) & x(2) & x(3))
    
  5. To set the default property value, use the variable name, with an argument list, on the left side of an assignment statement.

    VB
    x(1) = "Hello"
    x(2) = " "
    x(3) = "World"
    
  6. You can always specify the default property name together with the variable name, just as you would do to access any other property.

    VB
    x.myProperty(1) = "Hello"
    x.myProperty(2) = " "
    x.myProperty(3) = "World"
    

Example

The following example declares a default property on a class.

VB
Public Class class1
    Private myStrings() As String
    Sub New(ByVal size As Integer)
        ReDim myStrings(size)
    End Sub
    Default Property myProperty(ByVal index As Integer) As String
        Get
            ' The Get property procedure is called when the value
            ' of the property is retrieved.
            Return myStrings(index)
        End Get
        Set(ByVal Value As String)
            ' The Set property procedure is called when the value
            ' of the property is modified.
            ' The value to be assigned is passed in the argument 
            ' to Set.
            myStrings(index) = Value
        End Set
    End Property
End Class

Example

The following example demonstrates how to call the default property myProperty on class class1. The three assignment statements store values in myProperty, and the MsgBox call reads the values.

VB
Sub Test()
    Dim x As New class1(3)
    x(1) = "Hello"
    x(2) = " "
    x(3) = "World"
    MsgBox(x(1) & x(2) & x(3))
End Sub

The most common use of a default property is the Item[String] property on various collection classes.

Robust Programming

Default properties can result in a small reduction in source code-characters, but they can make your code more difficult to read. If the calling code is not familiar with your class or structure, when it makes a reference to the class or structure name it cannot be certain whether that reference accesses the class or structure itself, or a default property. This can lead to compiler errors or subtle run-time logic errors.

You can somewhat reduce the chance of default property errors by always using the Option Strict Statement to set compiler type checking to On.

If you are planning to use a predefined class or structure in your code, you must determine whether it has a default property, and if so, what its name is.

Because of these disadvantages, you should consider not defining default properties. For code readability, you should also consider always referring to all properties explicitly, even default properties.

See also

How to: Put a Value in a Property

You store a value in a property by putting the property name on the left side of an assignment statement.

The property's Set procedure stores a value, but you do not explicitly call it by name. You use the property just as you would use a variable. Visual Basic makes the calls to the property's procedures.

To store a value in a property

  1. Use the property name on the left side of an assignment statement.

    The following example sets the value of the Visual Basic TimeOfDay property to noon, implicitly calling its Set procedure.

    VB
    ' The following statement calls the Set procedure of the Visual Basic TimeOfDay property.
    TimeOfDay = #12:00:00 PM#
    
  2. If the property takes arguments, follow the property name with parentheses to enclose the argument list. If there are no arguments, you can optionally omit the parentheses.

  3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the arguments in the same order that the property defines the corresponding parameters.

  4. The value generated on the right side of the assignment statement is stored in the property.

See also

How to: Get a Value from a Property

You retrieve a property's value by including the property name in an expression.

The property's Get procedure retrieves the value, but you do not explicitly call it by name. You use the property just as you would use a variable. Visual Basic makes the calls to the property's procedures.

To retrieve a value from a property

  1. Use the property name in an expression the same way you would use a variable name. You can use a property anywhere you can use a variable or a constant.

    -or-

    Use the property name following the equal (=) sign in an assignment statement.

    The following example reads the value of the Visual Basic Now property, implicitly calling its Get procedure.

    VB
    Dim ThisMoment As Date
    ' The following statement calls the Get procedure of the Visual Basic Now property.
    ThisMoment = Now
    
  2. If the property takes arguments, follow the property name with parentheses to enclose the argument list. If there are no arguments, you can optionally omit the parentheses.

  3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the arguments in the same order that the property defines the corresponding parameters.

The value of the property participates in the expression just as a variable or constant would, or it is stored in the variable or property on the left side of the assignment statement.

See also

Operator Procedures

An operator procedure is a series of Visual Basic statements that define the behavior of a standard operator (such as *, <>, or And) on a class or structure you have defined. This is also called operator overloading.

When to Define Operator Procedures

When you have defined a class or structure, you can declare variables to be of the type of that class or structure. Sometimes such a variable needs to participate in an operation as part of an expression. To do this, it must be an operand of an operator.

Visual Basic defines operators only on its fundamental data types. You can define the behavior of an operator when one or both of the operands are of the type of your class or structure.

For more information, see Operator Statement.

Types of Operator Procedure

An operator procedure can be one of the following types:

  • A definition of a unary operator where the argument is of the type of your class or structure.

  • A definition of a binary operator where at least one of the arguments is of the type of your class or structure.

  • A definition of a conversion operator where the argument is of the type of your class or structure.

  • A definition of a conversion operator that returns the type of your class or structure.

Conversion operators are always unary, and you always use CType as the operator you are defining.

Declaration Syntax

The syntax for declaring an operator procedure is as follows:

VB
Public Shared [Widening | Narrowing] Operator operatorsymbol ( operand1 [,  operand2 ]) As datatype  
 
' Statements of the operator procedure.
 
End Operator

You use the Widening or Narrowing keyword only on a type conversion operator. The operator symbol is always CType Function for a type conversion operator.

You declare two operands to define a binary operator, and you declare one operand to define a unary operator, including a type conversion operator. All operands must be declared ByVal.

You declare each operand the same way you declare parameters for Sub Procedures.

Data Type

Because you are defining an operator on a class or structure you have defined, at least one of the operands must be of the data type of that class or structure. For a type conversion operator, either the operand or the return type must be of the data type of the class or structure.

For more details, see Operator Statement.

Calling Syntax

You invoke an operator procedure implicitly by using the operator symbol in an expression. You supply the operands the same way you do for predefined operators.

The syntax for an implicit call to an operator procedure is as follows:

Dim testStruct As structurename

Dim testNewStruct As structurename = testStruct operatorsymbol 10

Illustration of Declaration and Call

The following structure stores a signed 128-bit integer value as the constituent high-order and low-order parts. It defines the + operator to add two veryLong values and generate a resulting veryLong value.

VB
Public Structure veryLong
    Dim highOrder As Long
    Dim lowOrder As Long
    Public Shared Operator +(ByVal v As veryLong, 
                             ByVal w As veryLong) As veryLong
        Dim sum As New veryLong
        sum = v
        Try
            sum.lowOrder += w.lowOrder
        Catch ex As System.OverflowException
            sum.lowOrder -= (Long.MaxValue - w.lowOrder + 1)
            sum.highOrder += 1
        End Try
        sum.highOrder += w.highOrder
        Return sum
    End Operator
End Structure

The following example shows a typical call to the + operator defined on veryLong.

VB
Dim v1, v2, v3 As veryLong
v1.highOrder = 1
v1.lowOrder = Long.MaxValue
v2.highOrder = 0
v2.lowOrder = 4
v3 = v1 + v2

See also

How to: Define an Operator

If you have defined a class or structure, you can define the behavior of a standard operator (such as *, <>, or And) when one or both of the operands is of the type of your class or structure.

Define the standard operator as an operator procedure within the class or structure. All operator procedures must be Public Shared.

Defining an operator on a class or structure is also called overloading the operator.

Example

The following example defines the + operator for a structure called height. The structure uses heights measured in feet and inches. One inch is 2.54 centimeters, and one foot is 12 inches. To ensure normalized values (inches < 12.0), the constructor performs modulo 12 arithmetic. The + operator uses the constructor to generate normalized values.

VB
Public Shadows Structure height
    ' Need Shadows because System.Windows.Forms.Form also defines property Height.
    Private feet As Integer
    Private inches As Double
    Public Sub New(ByVal f As Integer, ByVal i As Double)
        Me.feet = f + (CInt(i) \ 12)
        Me.inches = i Mod 12.0
    End Sub
    Public Overloads Function ToString() As String
        Return Me.feet & "' " & Me.inches & """"
    End Function
    Public Shared Operator +(ByVal h1 As height, 
                             ByVal h2 As height) As height
        Return New height(h1.feet + h2.feet, h1.inches + h2.inches)
    End Operator
End Structure

You can test the structure height with the following code.

VB
Public Sub consumeHeight()
    Dim p1 As New height(3, 10)
    Dim p2 As New height(4, 8)
    Dim p3 As height = p1 + p2
    Dim s As String = p1.ToString() & " + " & p2.ToString() &
          " = " & p3.ToString() & " (= 8' 6"" ?)"
    Dim p4 As New height(2, 14)
    s &= vbCrLf & "2' 14"" = " & p4.ToString() & " (= 3' 2"" ?)"
    Dim p5 As New height(4, 24)
    s &= vbCrLf & "4' 24"" = " & p5.ToString() & " (= 6' 0"" ?)"
    MsgBox(s)
End Sub

See also

How to: Define a Conversion Operator

If you have defined a class or structure, you can define a type conversion operator between the type of your class or structure and another data type (such as Integer, Double, or String).

Define the type conversion as a CType Function procedure within the class or structure. All conversion procedures must be Public Shared, and each one must specify either Widening or Narrowing.

Defining an operator on a class or structure is also called overloading the operator.

Example

The following example defines conversion operators between a structure called digit and a Byte.

VB
Public Structure digit
Private dig As Byte
    Public Sub New(ByVal b As Byte)
        If (b < 0 OrElse b > 9) Then Throw New System.ArgumentException(
            "Argument outside range for Byte")
        Me.dig = b
    End Sub
    Public Shared Widening Operator CType(ByVal d As digit) As Byte
        Return d.dig
    End Operator
    Public Shared Narrowing Operator CType(ByVal b As Byte) As digit
        Return New digit(b)
    End Operator
End Structure

You can test the structure digit with the following code.

VB
Public Sub consumeDigit()
    Dim d1 As New digit(4)
    Dim d2 As New digit(7)
    Dim d3 As digit = CType(CByte(3), digit)
    Dim s As String = "Initial 4 generates " & CStr(CType(d1, Byte)) &
          vbCrLf & "Initial 7 generates " & CStr(CType(d2, Byte)) &
          vbCrLf & "Converted 3 generates " & CStr(CType(d3, Byte))
    Try
        Dim d4 As digit
        d4 = CType(CType(d1, Byte) + CType(d2, Byte), digit)
    Catch e4 As System.Exception
        s &= vbCrLf & "4 + 7 generates " & """" & e4.Message & """"
    End Try
    Try
        Dim d5 As digit = CType(CByte(10), digit)
    Catch e5 As System.Exception
        s &= vbCrLf & "Initial 10 generates " & """" & e5.Message & """"
    End Try
    MsgBox(s)
End Sub

See also

How to: Call an Operator Procedure

You call an operator procedure by using the operator symbol in an expression. In the case of a conversion operator, you call the CType Function to convert a value from one data type to another.

You do not call operator procedures explicitly. You just use the operator, or the CType function, in an assignment statement or an expression, the same way you ordinarily use an operator. Visual Basic makes the call to the operator procedure.

Defining an operator on a class or structure is also called overloading the operator.

To call an operator procedure

  1. Use the operator symbol in an expression in the ordinary way.

  2. Be sure the data types of the operands are appropriate for the operator, and in the correct order.

  3. The operator contributes to the value of the expression as expected.

To call a conversion operator procedure

  1. Use CType inside an expression.

  2. Be sure the data types of the operands are appropriate for the conversion, and in the correct order.

  3. CType calls the conversion operator procedure and returns the converted value.

Example

The following example creates two TimeSpan structures, adds them together, and stores the result in a third TimeSpan structure. The TimeSpan structure defines operator procedures to overload several standard operators.

VB
Dim firstSpan As New TimeSpan(3, 30, 0)
Dim secondSpan As New TimeSpan(1, 30, 30)
Dim combinedSpan As TimeSpan = firstSpan + secondSpan
Dim s As String = firstSpan.ToString() & 
          " + " & secondSpan.ToString() & 
          " = " & combinedSpan.ToString()
MsgBox(s)

Because TimeSpan overloads the standard + operator, the previous example calls an operator procedure when it calculates the value of combinedSpan.

For an example of calling a conversation operator procedure, see How to: Use a Class that Defines Operators.

Compiling the Code

Be sure the class or structure you are using defines the operator you want to use.

See also

How to: Use a Class that Defines Operators

If you are using a class or structure that defines its own operators, you can access those operators from Visual Basic.

Defining an operator on a class or structure is also called overloading the operator.

Example

The following example accesses the SQL structure SqlString, which defines the conversion operators (CType Function) in both directions between a SQL string and a Visual Basic string. Use CType(SQL string expression, String) to convert a SQL string to a Visual Basic string, and CType(Visual Basic string expression, SqlString) to convert in the other direction.

VB
' Insert the following line at the beginning of your source file.
Imports System.Data.SqlTypes
VB
Public Sub setJobString(ByVal g As Integer)
    Dim title As String
    Dim jobTitle As System.Data.SqlTypes.SqlString
    Select Case g
        Case 1
            title = "President"
        Case 2
            title = "Vice President"
        Case 3
            title = "Director"
        Case 4
            title = "Manager"
        Case Else
            title = "Worker"
    End Select
    jobTitle = CType(title, SqlString)
    MsgBox("Group " & CStr(g) & " generates title """ &
          CType(jobTitle, String) & """")
End Sub

The SqlString structure defines a conversion operator (CType Function) from String to SqlString and another from SqlString to String. The statement that assigns title to jobTitle makes use of the first operator, and the MsgBox function call uses the second.

Compiling the Code

Be sure the class or structure you are using defines the operator you want to use. Do not assume that the class or structure has defined every operator available for overloading. For a list of available operators, see Operator Statement.

Include the appropriate Imports statement for the SQL string at the beginning of your source file (in this case System.Data.SqlTypes).

Your project must have references to System.Data and System.XML.

See also

 

Source/Reference


©sideway

ID: 201000007 Last Updated: 7/10/2020 Revision: 0 Ref:

close

References

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

Home 5

Business

Management

HBR 3

Information

Recreation

Hobbies 8

Culture

Chinese 1097

English 337

Reference 67

Computer

Hardware 151

Software

Application 198

Digitization 25

Latex 9

Manim 121

Numeric 19

Programming

Web 283

Unicode 494

HTML 65

CSS 58

ASP.NET 174

OS 389

DeskTop 7

Python 19

Knowledge

Mathematics

Formulas 8

Algebra 25

Number Theory 206

Trigonometry 18

Geometry 21

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

Physics

Electric 27

Biology 1

Geography 1


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