Object Array
This page was last reviewed on Mar 20, 2022.
Dot Net Perls
Object array. 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.
Example. 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.
Detail An Object array of 5 elements is declared—each of the 5 elements is 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.
However You can still reference these types as Object types. They have their derived type, and their base types.
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
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.
Tip Object arrays give flexibility at the cost of performance, because elements must be cast or checked to be used.
A summary. 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.
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.
This page was last updated on Mar 20, 2022 (rewrite).
© 2007-2024 Sam Allen.