Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))

CObj Function

Syntax

Dim result As Object = CObj (expression)

expression (required; any)

Any expression

Description

The CObj function converts any expression that can be interpreted as an object to the Object data type.

Usage at a Glance

  • The operation of the CObj function is possible because all .NET data types derive from Object.

  • Once a data type is converted to type Object, you can display its value by calling its ToString method:

    Dim strongFlag As Boolean = True Dim weakData As Object = CObj(strongFlag) MsgBox(weakData.ToString( )) ' Displays "True"

  • Variables can be assigned to Object variables using direct assignment as well.

    Dim strongData As New SomeClass Dim weakData As Object weakData = strongData

  • This function does not support named arguments.

Example

The following code stores strongly typed data as an Object:

Dim strongData As New SomeClass Dim weakData As Object weakData = CObj(strongData)

Version Differences

The CObj function did not exist in VB 6. The closest equivalent in VB 6 was CVar, which converted a data type to a Variant.

Категории