SNag
SNag

Reputation: 18141

VB.NET How to declare new empty array of known length

Is there a way in VB.NET to declare an array, and later initialize it to a known length in the code? In other words, I'm looking for the VB.NET equivalent of the following C#.NET code:

string[] dest;
// more code here
dest = new string[src.Length];

I tried this in VB, and it didn't work.

Dim dest() as string
' more code here
dest = New String(src.Length)

What am I missing?


NOTE: I can confirm that

Dim dest(src.Length) as string

works, but is not what I want, since I'm looking to separate the declaration and initialization of the array.

Upvotes: 34

Views: 56889

Answers (3)

Abbas Amiri
Abbas Amiri

Reputation: 3204

The syntax of VB.NET in such a case is a little different. The equivalent of

string[] dest;
// more code here
dest = new string[src.Length];

is

Dim dest As String()
' more code here
dest = New String(src.Length - 1) {}

Syntax note

When you use Visual Basic syntax to define the size of an array, you specify its highest index, not the total number of elements in the array. learn.microsoft.com

Example

These two array both have a length of 5:

C#:
string[] a = new string[5];
VB: 
Dim a As String() = New String(4) {}

Upvotes: 61

Brian Hooper
Brian Hooper

Reputation: 22054

The normal way to do this would be to declare the array like so:-

Dim my_array() As String

and later in the code

ReDim my_array (src.Length - 1)

Upvotes: 9

Matt Wilko
Matt Wilko

Reputation: 27322

You can use Redim as already noted but this is the equivalent VB code to your C#

Dim dest As String()
dest = New String(src.Length - 1) {}

Try and avoid using dynamic arrays though. A generic List(Of T) is much more flexible

Upvotes: 5

Related Questions