Object. In VB.NET, programs must handle many types—and each of these types can be referred to as an Object. Object is the universal base class, and all classes are Objects.
With an Object parameter, we can handle many different types within a method. We can test objects with IsNothing and the Is-operator.
Example. Consider a Class like StringBuilder—we can refer to a StringBuilder as an Object. This is because the StringBuilder has Object as a base class (all types do).
Warning Usually it is best to refer to a Class by its most derived name (like StringBuilder) as this imparts the most information.
Imports System.Text
Module Module1
Sub Main()
' Use an object reference.
Dim val As Object = New StringBuilder()
Console.WriteLine(val.GetType())
End Sub
End ModuleSystem.Text.StringBuilder
Object parameter. To continue, we can specify a method (a subroutine) that receives a parameter of Object type. Then we can pass any Class or value to the method.
Part 1 We create a String and pass it to the Test() subroutine. It is acceptable to omit the DirectCast expression, as this is done automatically.
Part 2 Integers, which are values, are also considered Objects. We can pass them as an Object parameter.
Part 3 It is possible to use the special value Nothing (which is like null in C#) as an Object as well.
Module Module1
Sub Main()
' Part 1: use string type as object.
Dim value As String = "Example"
Test(value)
Test(DirectCast(value, Object))
' Part 2: use integer type as object.
Dim number As Integer = 100
Test(number)
Test(DirectCast(number, Object))
' Part 3: use Nothing object.
Test(Nothing)
End Sub
Sub Test(ByVal value As Object)
' Test the object.
If IsNothing(value)
Console.WriteLine("Nothing")
Else If TypeOf value Is String
Console.WriteLine($"String value: {value}")
Else If TypeOf value Is Integer
Console.WriteLine($"Integer value: {value}")
End If
End Sub
End ModuleString value: Example
String value: Example
Integer value: 100
Integer value: 100
Nothing
With the Object type, we have a way to reference any Class in the VB.NET language. But in most programs, using Object types makes programs harder to work with and even slower.
With generic classes like Dictionary or List, we can avoid using Objects and instead use the actual type. This imparts a performance advantage, and is also easier to maintain.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.