How to Create Dynamic Array in Vb.Net

Leave a Comment

To declare a dynamic array with empty parentheses you use the Dim statement. Dynamic array can be dimensioned or dimensioned again as you need them by using the ReDim statement (which you must do the first time you want to use a dynamic array).

Syntax

ReDim [Preserve] varname(subscripts)
The Preserve keyword is used to preserve the data in the existing array when you change the size of the last dimension. The varname argument holds the name of the array to dimension again. The subscripts term specifies the new dimension of the array.

Create Dynamic Array

Dim DynaArr( As String
ReDim DynaArr(10)
DynaArr(0) = "String 0"
Nees more data space!
ReDim DynaArr(100)
DynaArr(50) = "String 50"

In the above code we create an array, dimension it size 10, and then again re-dimension it to size 100.

Example

Imports System
Module Module1
Sub Main()
Dim counter As Integer
        Dim studentName() As String
        ReDim studentName(3)
        Console.WriteLine("Enter the Student Names")
        For counter = 0 To 2
            Console.Write("Student " & (counter + 1) & " : ")
            studentName(counter) = Console.ReadLine()
        Next counter
        ReDim Preserve studentName(5)
        For counter = 3 To 4
            Console.Write("Student " & (counter + 1) & " : ")
            studentName(counter) = Console.ReadLine()
        Next counter
        Console.WriteLine("The Student Names are:")
        For counter = 0 To 4
            Console.WriteLine(studentName(counter))
        Next counter
End Sub
End Module

0 comments:

Post a Comment