Type Operators

 <  Day Day Up  >  

The TypeOf operator determines whether a value is of a particular type or is derived from a particular type. This is particularly useful when you are dealing with values typed only as Object , or when working with types in an inheritance hierarchy. In the following example, a function that takes an Object value uses the TypeOf operator to determine the actual type of the value.

 Function AddOne(ByVal o As Object) As Object   If TypeOf o Is Integer Then     Return CInt(o) + 1   ElseIf TypeOf o Is Double Then     Return CDbl(o) + 1   ' Handle the other types   ...   Else     Throw New ArgumentException("Not a recognized value.")   End If End Function 

Advanced

Because it is not possible to derive from a value type (see Chapter 9), the TypeOf operator has no meaning for value types and is not allowed. (A value typed as a value type can never be anything but itself.) It is possible to test whether a value typed as Object is a value type, because a value type can always be converted to Object .


Style

Using TypeOf to determine the exact value of a type will be much faster at runtime than attempting to convert the value and handling a resulting exception.


The GetType operator returns an instance of the System.Type class that represents the specified type. The System.Type class is a .NET Framework reflection class that can be used to inspect a type and its members at runtime. It can also be used with other reflection classes to do things like create instances of the class dynamically.

 Dim t As Type Dim c As Collection t = GetType(Collection) c = Activator.CreateInstance(t) 

This example dynamically creates an instance of the Collection class at runtime.

 <  Day Day Up  >  


The Visual Basic .NET Programming Language
The Visual Basic .NET Programming Language
ISBN: 0321169514
EAN: 2147483647
Year: 2004
Pages: 173
Authors: Paul Vick

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net