Dynamic Array using ReDim in VB.Net

Leave a Comment

To Declare a dynamic array with empty parentheses, you can use the Dim statement. Dynamic arrays 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.) The following is the syntax for using the ReDim statement:
ReDim [Preserve] varname(subscripts)

The Preserve keyword is ued to preserve the data in an existing aray 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.

The following code snippest shows how to create dynamic arrays:
Dim DynArr() As String
ReDim DynaArr(10)
DynaArr(0) = "String 0"
'Need more data space!
ReDim DynaArr(100)
DynaArr(50) = "String 50"

In the preceding code snippet, we declare an array, dimension it with size 10, and then again re-dimension it to size 100.

Let's create a VB.NET prorgram. DynamicArray.vb
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