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.
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 ModuleSystem.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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 3, 2024 (edit link).