HomeSearch

VB.NET Object Array

Use Object arrays to store many types of elements. Cast elements in Object arrays.

Object array. 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. We gain a great degree of flexibility when the type system is used in this way.Array

Note: With an Object array, a Function can accept any number of arguments—of any type.

Example. There are two 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 the Console.WriteLine function.

Main: An Object array of 5 elements is declared. Each of the 5 elements are assigned to an Object.

Info: The elements in the Object array are all of type Object, but they also have more derived types, including StringBuilder, String, and Int32.

StringBuilderStringsInteger

However: You can still reference these types as Object types. They have their derived type, and their base types.

VB.NET program that creates Object array 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 Module Output System.Object System.Object --- Initialized System.Text.StringBuilder --- Literal System.String --- 6 System.Int32 ---

Testing against Nothing. 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.

Summary. The VB.NET language uses a powerful type hierarchy, which enables you to reference more derived types as their base type (Object). Because of this, you can easily store many different types inside an Object array.

Tip: This gives you great flexibility at the cost of performance, because elements must then be cast or checked again to be used.

Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.