Sideway
output.to from Sideway
Draft for Information Only

Content

VB.NET Object Variable Declaration
 Declaration Syntax
 Late Binding and Early Binding
  Advantages of Early Binding
 Access to Object Variable Members
 Flexibility of Object Variables
 See also
  How to: Access Members of an Object
 Accessing Members
   To access members of an object
 Accessing Members of an Object of Known Type
   To access members of an object for which you know the type at compile time
 Accessing Members of an Object of Unknown Type
   To access members of an object for which you do not know the type at compile time
 See also
  Object Variable Assignment
 Initialization
 Disassociation
 Current Instance
 See also
  How to: Declare an Object Variable and Assign an Object to It
 Example
 Compiling the Code
 See also
  How to: Make an Object Variable Not Refer to Any Instance
  To disassociate an object variable from any object instance
 Robust Programming
 .NET Framework Security
 See also
  Object Variable Values
 Object Classifier Functions
 TypeOf Operator
 Object Arrays
 See also
  How to: Refer to the Current Instance of an Object
  To refer to the current instance
 See also
  How to: Determine What Type an Object Variable Refers To
  To determine the exact type an object variable currently refers to
  To determine whether an object variable's type is compatible with a specified type
 Compiling the Code
 See also
  How to: Determine Whether Two Objects Are Related
  To determine if one object inherits from another object's class or interface
 Example
 See also
  How to: Determine Whether Two Objects Are Identical
 Determining if Two Objects Are Identical
   To determine if two objects are identical
 Determining if Two Objects Are Not Identical
   To determine if two objects are not identical
 Example
 See also
  Source/Reference

VB.NET Object Variable Declaration

You use a normal declaration statement to declare an object variable. For the data type, you specify either Object (that is, the Object Data Type) or a more specific class from which the object is to be created.

Declaring a variable as Object is the same as declaring it as System.Object.

When you declare a variable with a specific object class, it can access all the methods and properties exposed by that class and the classes from which it inherits. If you declare the variable with Object, it can access only the members of the Object class, unless you turn Option Strict Off to allow late binding.

Declaration Syntax

Use the following syntax to declare an object variable:

VB
Dim variablename As [New] { objectclass | Object }  

You can also specify Public, Protected, Friend, Protected Friend, Private, Shared, or Static in the declaration. The following example declarations are valid:

VB
Private objA As Object  
Static objB As System.Windows.Forms.Label  
Dim objC As System.OperatingSystem  

Late Binding and Early Binding

Sometimes the specific class is unknown until your code runs. In this case, you must declare the object variable with the Object data type. This creates a general reference to any type of object, and the specific class is assigned at run time. This is called late binding. Late binding requires additional execution time. It also limits your code to the methods and properties of the class you have most recently assigned to it. This can cause run-time errors if your code attempts to access members of a different class.

When you know the specific class at compile time, you should declare the object variable to be of that class. This is called early binding. Early binding improves performance and guarantees your code access to all the methods and properties of the specific class. In the preceding example declarations, if variable objA uses only objects of class System.Windows.Forms.Label, you should specify As System.Windows.Forms.Label in its declaration.

Advantages of Early Binding

Declaring an object variable as a specific class gives you several advantages:

  • Automatic type checking

  • Guaranteed access to all members of the specific class

  • Microsoft IntelliSense support in the Code Editor

  • Improved readability of your code

  • Fewer errors in your code

  • Errors caught at compile time rather than run time

  • Faster code execution

Access to Object Variable Members

When Option Strict is turned On, an object variable can access only the methods and properties of the class with which you declare it. The following example illustrates this.

VB
' Option statements must precede all other source file lines.  
Option Strict On  
' Imports statement must precede all declarations in the source file.  
Imports System.Windows.Forms  
Public Sub accessMembers()  
    Dim p As Object  
    Dim q As System.Windows.Forms.Label  
    p = New System.Windows.Forms.Label  
    q = New System.Windows.Forms.Label  
    Dim j, k As Integer  
    ' The following statement generates a compiler ERROR.  
    j = p.Left  
    ' The following statement retrieves the left edge of the label in pixels.  
    k = q.Left  
End Sub  

In this example, p can use only the members of the Object class itself, which do not include the Left property. On the other hand, q was declared to be of type Label, so it can use all the methods and properties of the Label class in the System.Windows.Forms namespace.

Flexibility of Object Variables

When working with objects in an inheritance hierarchy, you have a choice of which class to use for declaring your object variables. In making this choice, you must balance flexibility of object assignment against access to members of a class. For example, consider the inheritance hierarchy that leads to the System.Windows.Forms.Form class:

Object

  MarshalByRefObject

    Component

      Control

        ScrollableControl

          ContainerControl

            Form

Suppose your application defines a form class called specialForm, which inherits from class Form. You can declare an object variable that refers specifically to specialForm, as the following example shows.

VB
Public Class specialForm  
    Inherits System.Windows.Forms.Form  
    ' Insert code defining methods and properties of specialForm.  
End Class  
Dim nextForm As New specialForm  

The declaration in the preceding example limits the variable nextForm to objects of class specialForm, but it also makes all the methods and properties of specialForm available to nextForm, as well as all the members of all the classes from which specialForm inherits.

You can make an object variable more general by declaring it to be of type Form, as the following example shows.

VB
Dim anyForm As System.Windows.Forms.Form  

The declaration in the preceding example lets you assign any form in your application to anyForm. However, although anyForm can access all the members of class Form, it cannot use any of the additional methods or properties defined for specific forms such as specialForm.

All the members of a base class are available to derived classes, but the additional members of a derived class are unavailable to the base class.

See also

How to: Access Members of an Object

When you have an object variable that refers to an object, you often want to work with the members of that object, such as its methods, properties, fields, and events. For example, once you have created a new Form object, you might want to set its Text property or call its Focus method.

Accessing Members

You access an object's members through the variable that refers to it.

To access members of an object

  • Use the member-access operator (.) between the object variable name and the member name.

    VB
  • currentText = newForm.Text
    

    If the member is Shared, you do not need a variable to access it.

Accessing Members of an Object of Known Type

If you know the type of an object at compile time, you can use early binding for a variable that refers to it.

To access members of an object for which you know the type at compile time

  1. Declare the object variable to be of the type of the object you intend to assign to the variable.

    VB
    Dim extraForm As System.Windows.Forms.Form
    

    With Option Strict On, you can assign only Form objects (or objects of a type derived from Form) to extraForm. If you have defined a class or structure with a widening CType conversion to Form, you can also assign that class or structure to extraForm.

  2. Use the member-access operator (.) between the object variable name and the member name.

    VB
    extraForm.Show()
    

    You can access all of the methods and properties specific to the Form class, no matter what the Option Strict setting is.

Accessing Members of an Object of Unknown Type

If you do not know the type of an object at compile time, you must use late binding for any variable that refers to it.

To access members of an object for which you do not know the type at compile time

  1. Declare the object variable to be of the Object Data Type. (Declaring a variable as Object is the same as declaring it as System.Object.)

    VB
    Dim someControl As Object
    

    With Option Strict On, you can access only the members that are defined on the Object class.

  2. Use the member-access operator (.) between the object variable name and the member name.

    VB
    someControl.GetType()
    

    To be able to access the members of any object you assign to the object variable, you must set Option Strict Off. When you do this, the compiler cannot guarantee that a given member is exposed by the object you assign to the variable. If the object does not expose a member you attempt to access, a MemberAccessException exception occurs.

See also

Object Variable Assignment

You use a normal assignment statement to assign an object to an object variable. You can assign an object expression or the Nothing keyword, as the following example illustrates.

VB
Dim thisObject As Object
' The following statement assigns an object reference.
thisObject = Form1
' The following statement discontinues association with any object.
thisObject = Nothing

Nothing means there is no object currently assigned to the variable.

Initialization

When your code begins running, your object variables are initialized to Nothing. Those whose declarations include initialization are reinitialized to the values you specify when the declaration statements are executed.

You can include initialization in your declaration by using the New keyword. The following declaration statements declare object variables testUri and ver and assign specific objects to them. Each uses one of the overloaded constructors of the appropriate class to initialize the object.

VB
Dim testUri As New System.Uri("https://www.microsoft.com")
Dim ver As New System.Version(6, 1, 0)

Disassociation

Setting an object variable to Nothing discontinues the association of the variable with any specific object. This prevents you from accidentally changing the object by changing the variable. It also allows you to test whether the object variable points to a valid object, as the following example shows.

VB
If otherObject IsNot Nothing Then
    ' otherObject refers to a valid object, so your code can use it.
End If

If the object your variable refers to is in another application, this test cannot determine whether that application has terminated or just invalidated the object.

An object variable with a value of Nothing is also called a null reference.

Current Instance

The current instance of an object is the one in which the code is currently executing. Since all code executes inside a procedure, the current instance is the one in which the procedure was invoked.

The Me keyword acts as an object variable referring to the current instance. If a procedure is not Shared, it can use the Me keyword to obtain a pointer to the current instance. Shared procedures cannot be associated with a specific instance of a class.

Using Me is particularly useful for passing the current instance to a procedure in another module. For example, suppose you have a number of XML documents and wish to add some standard text to all of them. The following example defines a procedure to do this.

VB
Sub addStandardText(XmlDoc As System.Xml.XmlDocument)
    XmlDoc.CreateTextNode("This text goes into every XML document.")
End Sub

Every XML document object could then call the procedure and pass its current instance as an argument. The following example demonstrates this.

VB
addStandardText(Me)

See also

How to: Declare an Object Variable and Assign an Object to It

You declare a variable of the Object Data Type by specifying As Object in a Dim Statement. You assign an object to such a variable by placing the object after the equal sign (=) in an assignment statement or initialization clause.

Example

The following example declares an Object variable and assigns the current instance to it.

VB
Dim thisObject As Object
thisObject = "This is an Object"

You can combine the declaration and assignment by initializing the variable as part of its declaration. The following example is equivalent to the preceding example.

VB
Dim thisObject As Object= "This is an Object"

Compiling the Code

This example requires:

  • A reference to the System namespace.

  • A class, structure, or module in which to put the Dim statement.

  • A procedure in which to put the assignment statement.

See also

How to: Make an Object Variable Not Refer to Any Instance

You can disassociate an object variable from any object instance by setting it to Nothing.

To disassociate an object variable from any object instance

  • Set the variable to Nothing in an assignment statement.

  • ' Assume account is a defined class  
    Dim currentAccount As account  
    currentAccount = Nothing  
    

Robust Programming

If your code tries to access a member of an object variable that has been set to Nothing, a NullReferenceException occurs. If you set an object variable to Nothing frequently, or if it is possible the variable is not initialized, it is a good idea to enclose member accesses in a Try...Catch...Finally block.

.NET Framework Security

If you use an object variable for objects that contain confidential or sensitive data, you can set the variable to Nothing when you are not actively dealing with one of those objects. This reduces the chance of malicious code gaining access to the data.

See also

Object Variable Values

A variable of the Object Data Type can refer to data of any type. The value you store in an Object variable is kept elsewhere in memory, while the variable itself holds a pointer to the data.

Object Classifier Functions

Visual Basic supplies functions that return information about what an Object variable refers to, as shown in the following table.

Function Returns True if the Object variable refers to
IsArray An array of values, rather than a single value
IsDate A Date Data Type value, or a string that can be interpreted as a date and time value
IsDBNull An object of type DBNull, which represents missing or nonexistent data
IsError An exception object, which derives from Exception
IsNothing Nothing, that is, no object is currently assigned to the variable
IsNumeric A number, or a string that can be interpreted as a number
IsReference A reference type (such as a string, array, delegate, or class type)

You can use these functions to avoid submitting an invalid value to an operation or a procedure.

TypeOf Operator

You can also use the TypeOf Operator to determine whether an object variable currently refers to a specific data type. The TypeOf...Is expression evaluates to True if the run-time type of the operand is derived from or implements the specified type.

The following example uses TypeOf on object variables referring to value and reference types.

' The following statement puts a value type (Integer) in an Object variable.  
Dim num As Object = 10  
' The following statement puts a reference type (Form) in an Object variable.  
Dim frm As Object = New Form()  
If TypeOf num Is Long Then Debug.WriteLine("num is Long")  
If TypeOf num Is Integer Then Debug.WriteLine("num is Integer")  
If TypeOf num Is Short Then Debug.WriteLine("num is Short")  
If TypeOf num Is Object Then Debug.WriteLine("num is Object")  
If TypeOf frm Is Form Then Debug.WriteLine("frm is Form")  
If TypeOf frm Is Label Then Debug.WriteLine("frm is Label")  
If TypeOf frm Is Object Then Debug.WriteLine("frm is Object")  

The preceding example writes the following lines to the Debug window:

num is Integer

num is Object

frm is Form

frm is Object

The object variable num refers to data of type Integer, and frm refers to an object of class Form.

Object Arrays

You can declare and use an array of Object variables. This is useful when you need to handle a variety of data types and object classes. All the elements in an array must have the same declared data type. Declaring this data type as Object allows you to store objects and class instances alongside other data types in the array.

See also

How to: Refer to the Current Instance of an Object

The current instance of an object is the instance in which the code is currently executing.

You use the Me keyword to refer to the current instance.

To refer to the current instance

  • Use the Me keyword where you would normally use the name of an object variable.

  • Me.ForeColor = System.Drawing.Color.Crimson  
    Me.Close()  
    

    Although Me behaves like an object variable, you cannot declare it or assign anything to it. Me always refers to the current instance.

See also

How to: Determine What Type an Object Variable Refers To

An object variable contains a pointer to data that is stored elsewhere. The type of that data can change during run time. At any moment, you can use the GetTypeCode method to determine the current run-time type, or the TypeOf Operator to find out if the current run-time type is compatible with a specified type.

To determine the exact type an object variable currently refers to

  1. On the object variable, call the GetType method to retrieve a System.Type object.

    VB
    Dim myObject As Object
    myObject.GetType()
    
  2. On the System.Type class, call the shared method GetTypeCode to retrieve the TypeCode enumeration value for the object's type.

    VB
    Dim myObject As Object
    Dim datTyp As Integer = Type.GetTypeCode(myObject.GetType())
    MsgBox("myObject currently has type code " & CStr(datTyp))
    

    You can test the TypeCode enumeration value against whichever enumeration members are of interest, such as Double.

To determine whether an object variable's type is compatible with a specified type

  • Use the TypeOf operator in combination with the Is Operator to test the object with a TypeOf...Is expression.

    VB
  • If TypeOf objA Is System.Windows.Forms.Control Then
        MsgBox("objA is compatible with the Control class")
    End If
    

    The TypeOf...Is expression returns True if the object's run-time type is compatible with the specified type.

    The criterion for compatibility depends on whether the specified type is a class, structure, or interface. In general, the types are compatible if the object is of the same type as, inherits from, or implements the specified type. For more information, see TypeOf Operator.

Compiling the Code

Note that the specified type cannot be a variable or expression. It must be the name of a defined type, such as a class, structure, or interface. This includes intrinsic types such as Integer and String.

See also

How to: Determine Whether Two Objects Are Related

You can compare two objects to determine the relationship, if any, between the classes from which they are created. The IsInstanceOfType method of the System.Type class returns True if the specified class inherits from the current class, or if the current type is an interface supported by the specified class.

To determine if one object inherits from another object's class or interface

  1. On the object you think might be of the base type, invoke the GetType method.

  2. On the System.Type object returned by GetType, invoke the IsInstanceOfType method.

  3. In the argument list for IsInstanceOfType, specify the object you think might be of the derived type.

    IsInstanceOfType returns True if its argument type inherits from the System.Type object type.

Example

The following example determines whether one object represents a class derived from another object's class.

VB
Public Class baseClass
End Class
Public Class derivedClass : Inherits baseClass
End Class
Public Class testTheseClasses
    Public Sub seeIfRelated()
        Dim baseObj As Object = New baseClass()
        Dim derivedObj As Object = New derivedClass()
        Dim related As Boolean
        related = baseObj.GetType().IsInstanceOfType(derivedObj)
        MsgBox(CStr(related))
    End Sub
End Class

Note the unexpected placement of the two object variables in the call to IsInstanceOfType. The supposed base type is used to generate the System.Type class, and the supposed derived type is passed as an argument to the IsInstanceOfType method.

See also

How to: Determine Whether Two Objects Are Identical

In Visual Basic, two variable references are considered identical if their pointers are the same, that is, if both variables point to the same class instance in memory. For example, in a Windows Forms application, you might want to make a comparison to determine whether the current instance (Me) is the same as a particular instance, such as Form2.

Visual Basic provides two operators to compare pointers. The Is Operator returns True if the objects are identical, and the IsNot Operator returns True if they are not.

Determining if Two Objects Are Identical

To determine if two objects are identical

  1. Set up a Boolean expression to test the two objects.

  2. In your testing expression, use the Is operator with the two objects as operands.

    Is returns True if the objects point to the same class instance.

Determining if Two Objects Are Not Identical

Sometimes you want to perform an action if the two objects are not identical, and it can be awkward to combine Not and Is, for example If Not obj1 Is obj2. In such a case you can use the IsNot operator.

To determine if two objects are not identical

  1. Set up a Boolean expression to test the two objects.

  2. In your testing expression, use the IsNot operator with the two objects as operands.

    IsNot returns True if the objects do not point to the same class instance.

Example

The following example tests pairs of Object variables to see if they point to the same class instance.

VB
Dim objA, objB, objC As Object
objA = My.User
objB = New ApplicationServices.User
objC = My.User
MsgBox("objA different from objB? " & CStr(objA IsNot objB))
MsgBox("objA identical to objC? " & CStr(objA Is objC))

The preceding example displays the following output.

objA different from objB? True

objA identical to objC? True

See also

 

Source/Reference

 


©sideway

ID: 200900008 Last Updated: 9/8/2020 Revision: 0 Ref:

close

References

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

Latest Updated LinksValid XHTML 1.0 Transitional Valid CSS!Nu Html Checker Firefox53 Chromena IExplorerna
IMAGE

Home 5

Business

Management

HBR 3

Information

Recreation

Hobbies 8

Culture

Chinese 1097

English 339

Reference 79

Computer

Hardware 249

Software

Application 213

Digitization 32

Latex 52

Manim 205

KB 1

Numeric 19

Programming

Web 289

Unicode 504

HTML 66

CSS 65

SVG 46

ASP.NET 270

OS 429

DeskTop 7

Python 72

Knowledge

Mathematics

Formulas 8

Algebra 84

Number Theory 206

Trigonometry 31

Geometry 34

Coordinate Geometry 2

Calculus 67

Complex Analysis 21

Engineering

Tables 8

Mechanical

Mechanics 1

Rigid Bodies

Statics 92

Dynamics 37

Fluid 5

Fluid Kinematics 5

Control

Process Control 1

Acoustics 19

FiniteElement 2

Natural Sciences

Matter 1

Electric 27

Biology 1

Geography 1


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