VB.Net - ReDim

This is not possible in C#.
You can only use ReDim after static declaration in VB.NET.
Only the last dimension can be resized.

Dim myarray(6) As Integer 
Redim myarray(4) As Integer

You cannot use ReDim as an array declaration in VB.NET


It is not possible to declare an array using the ReDim statement in .NET as it is in VBA.
You always have to declare the array before its dimension can be changed.

Dim aiArrayIntegers(10) As Integer 
ReDim aiArrayIntegers(20)

Because the ReDim cannot be used to declare an array it no longer supports the "As" keyword.
The ReDim can only be used to change the number of elements in the last dimension of the array.
You can still use ReDim Preserve to keep the elements already in an array.


ReDim

The use of ReDim for allocating a new array is necessary because VB does not allow the use of "New" when working with arrays (except with the curly bracket notation).

Dim asArray(,) As String 
ReDim asArray(500,4)


ReDim Preserve

Allows you to allocate a new array with new dimensions and copy all the elements from the old array to the new one in a single line of code


Dim asArray() As String = {"one","two","three"} 
ReDim Preserve asArray(10)

What is actually happening here is that a brand new array is created and then the System.Array.Copy method is called
The equivalent in C# would be:

string[] asArray = {"one","two","three"}; 
string[] temp = new string[10];
System.Array.Copy(asArray, 0, temp, 0, asArray.Length);
asArray = temp;

Rank

One of the problems with VB was that using the ReDim statement allowed the dimesions of an array to be changed.
This created inefficient code because it always had to check how many dimensions the array had before accessing any of its elements.
To create more efficient code VB.NET introduces the concept of a rank, which is the number dimensions in the array.
VB.NET allows you to change the number of items in an array but it does not let you change the rank of the array.
You specify the rank (i.e. the number of dimensions) when you declare the array.

Dim aiArrayIntegers() As Integer 
Dim aiArrayIntegers(,) As Integer
Dim aiArrayIntegers(,,) As Integer


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext