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.
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).
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
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.
String
and pass it to the Test()
subroutine. It is acceptable to omit the DirectCast
expression, as this is done automatically.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.