VB.NET Array Examples, String Arrays - Dot Net Perls
Có thể bạn quan tâm
In an array, one element is stored after another. And with For Each, we can loop over these elements. The size of a VB.NET array cannot be changed once created.
Other collections are built with internal arrays. There are many ways to initialize arrays. We can use Array class methods to change them.
String array
A string array is created in various ways. In the VB.NET language we can create the array with all its data in an initialization statement.
Version 1 The first array is created with an initialization statement. We do not need to specify the size of the array on the left side.Version 2 The next array uses the longer syntax. You must specify the capacity of the array in the Dim statement.Info We loop over the arrays with For Each. And we pass the arrays to a Sub M(), which prints their Lengths.First and last
We get the first element with the index 0. For the last element, we take the array Length and subtract one. This works on all non-empty, non-Nothing arrays.
Warning Arrays that are Nothing will cause a NullReferenceException to occur if you access elements on them.Also An empty array (one with zero elements) has no first or last element, so this code also will fail.For-loop
We can use the For-loop construct. This allows us to access the index of each element. This is useful for additional computations or logic.
Also Using the For-loop syntax is better for when you need to modify elements within the array.For Each, integers
This example creates an integer array. It specifies the maximum index in the first statement—we specify the maximum index, not the actual array element count.
Then We use For Each to enumerate its elements in order. This is clearer code than For.Module Module1 Sub Main() ' Create an array. Dim array(2) As Integer array(0) = 100 array(1) = 10 array(2) = 1 For Each element As Integer In array Console.WriteLine(element) Next End Sub End Module100 10 1Integer array, initializer
Often we can initialize an array with a single expression. Here we use the curly-bracket initializer syntax to create an array of 3 elements.
Module Module1 Sub Main() ' Create array of 3 integers. Dim array() As Integer = {10, 30, 50} For Each element As Integer In array Console.WriteLine(element) Next End Sub End Module10 30 50Array argument
We can pass an array to a subroutine or function. Please note that the entire array is not copied. Just a reference to the array is copied.
Detail When we pass the array ByVal, we can still modify the array's elements and have them changed elsewhere in the program.Module Module1 Sub Main() Dim array() As Integer = {5, 10, 20} ' Pass array as argument. Console.WriteLine(Example(array)) End Sub ''' <summary> ''' Receive array parameter. ''' </summary> Function Example(ByVal array() As Integer) As Integer Return array(0) + 10 End Function End Module15Return
We can return an array. This program shows the correct syntax. The Example() function creates a two-element array and then returns it.
Then The Main subroutine displays all the returned results by calling String.Join on them.Module Module1 Sub Main() Console.WriteLine(String.Join(",", Example())) End Sub ''' <summary> ''' Return array. ''' </summary> Function Example() As String() Dim array(1) As String array(0) = "Perl" array(1) = "Python" Return array End Function End ModulePerl,PythonIf-test
Often we must check that an index is valid—that it exists within the array. We can use an If-statement. Here we check that the index 2 is less than the length (which is 3).
So The index 2 can be safely accessed. But the index 50, tried next, causes an IndexOutOfRangeException.Module Module1 Sub Main() Dim values() As Integer = {5, 10, 15} ' Check that index is a valid position in array. If 2 < values.Length Then Console.WriteLine(values(2)) End If ' This causes an exception. Dim value = values(50) End Sub End Module15 Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.Length, LongLength
An array stores its element count. The Length property returns this count as an Integer. LongLength, useful for large arrays, returns a Long value.
Note The length of every array is stored directly inside the array object. It is not computed when we access it. This makes it fast.Module Module1 Sub Main() ' Create an array of 3 strings. Dim array() As String = {"Dot", "Net", "Perls"} Console.WriteLine(array.Length) Console.WriteLine(array.LongLength) ' Change the array to have two strings. array = {"OK", "Computer"} Console.WriteLine(array.Length) Console.WriteLine(array.LongLength) End Sub End Module3 3 2 2Empty array
How does one create an empty array in VB.NET? We specify the maximum index -1 when we declare the array—this means zero elements.
Detail To test for an empty array, use an If-statement and access the Length property, comparing it against 0.Module Module1 Sub Main() ' Create an empty array. Dim array(-1) As Integer ' Test for empty array. If array.Length = 0 Then Console.WriteLine("ARRAY IS EMPTY") End If End Sub End ModuleARRAY IS EMPTYObject arrays
In VB.NET, Strings inherit from the Object class. So we can pass an array of Strings to a method that requires an array of Objects.
Module Module1 Sub Main() ' Use string array as an object array. PrintLength(New String() {"Mac", "PC", "Android"}) End Sub Sub PrintLength(ByVal array As Object()) Console.WriteLine("OBJECTS: {0}", array.Length) End Sub End ModuleOBJECTS: 3IEnumerable
Arrays in VB.NET implement the IEnumerable interface (as does the List type). So we can pass an array to a method that accepts an IEnumerable.
Info We can then loop over the elements in the IEnumerable argument with For Each.Module Module1 Sub Main() ' Pass an array to a method that requires an IEnumerable. LoopOverItems(New Integer() {100, 500, 0}) End Sub Sub LoopOverItems(ByVal items As IEnumerable) ' Use For Each loop over IEnumerable argument. For Each item In items Console.WriteLine("ITEM: {0}", item) Next End Sub End ModuleITEM: 100 ITEM: 500 ITEM: 0Benchmark, array creation
Should we just use Lists instead of arrays in all places? The List generic in VB.NET has an additional performance cost over an equivalent array.
Version 1 This code creates many zero-element Integer arrays and then tests their Lengths.Version 2 Here we create many zero-element (empty) Integer Lists, and then we access their Count properties.Result Creating an array is faster than creating an equivalent List. Consider replacing Lists with arrays in hot code.Module Module1 Sub Main() Dim m As Integer = 10000000 ' Version 1: create an empty Integer array. Dim s1 As Stopwatch = Stopwatch.StartNew For i As Integer = 0 To m - 1 Dim array(-1) As Integer If array.Length <> 0 Then Return End If Next s1.Stop() ' Version 2: create an empty List of Integers. Dim s2 As Stopwatch = Stopwatch.StartNew For i As Integer = 0 To m - 1 Dim list As List(Of Integer) = New List(Of Integer)() If list.Count <> 0 Then Return End If Next s2.Stop() Dim u As Integer = 1000000 Console.WriteLine(((s1.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns")) Console.WriteLine(((s2.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns")) End Sub End Module3.68 ns array(-1) 10.46 ns New ListArrays are an important type. They are used inside other types, such as List and Dictionary, to implement those types storage. They are often faster.
Từ khóa » Visual Basic Array Integer
-
Arrays - Visual Basic | Microsoft Docs
-
VB.Net - Arrays - Tutorialspoint
-
Visual Basic (VB) Arrays - Tutlane
-
VB.NET Arrays - Javatpoint
-
Lesson 16 : Arrays - Visual Basic Tutorial
-
VB.Net Arrays: String, Dynamic With EXAMPLES - Guru99
-
How Do I Declare An Array Of Type Integer In ? - Stack Overflow
-
Arrays Are Using For Store Similar Data Types ... - Net
-
Using Visual Basic 6 -- Ch 11 --Working With Arrays
-
Visual Basic Arrays - Techotopia
-
Visual Basic Arrays - ZetCode
-
Visual Basic .NET Language Tutorial - Array - SO Documentation
-
Array Migration From VB6 To VB.NET And C# - Mobilize.Net