In VB.NET every variable or value derives from the Object type. Because of this, if we use an Object array, we can store multiple elements of any type.
With an Object array, a Function can accept any number of arguments—of any type. We gain a great degree of flexibility when the type system is used in this way.
There are 2 subroutines in this program. The Main
sub is the program's entry point. And in Write, we loop over an Object array and display each element with Console.WriteLine
.
StringBuilder
, String
, and Int32
.Imports System.Text Module Module1 Sub Main() ' Create an array of five elements. Dim arr(4) As Object arr(0) = New Object() arr(1) = New StringBuilder("Initialized") arr(2) = "Literal" arr(3) = 6 arr(4) = Nothing ' Pass array to Subroutine. Write(arr) End Sub Sub Write(ByVal arr() As Object) ' Loop over each element. For Each element As Object In arr ' Avoid Nothing elements. If element IsNot Nothing Then Console.WriteLine(element) Console.WriteLine(element.GetType()) Console.WriteLine("---") End If Next End Sub End ModuleSystem.Object System.Object --- Initialized System.Text.StringBuilder --- Literal System.String --- 6 System.Int32 ---
The Object array can contain references with value Nothing. To avoid accessing these Nothing elements, we use the IsNot
operator and compare against the Nothing literal.
The VB.NET language uses a powerful type hierarchy, which enables us to reference more derived types as their base type. We can store many different types inside an Object array.