Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

vb.net

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.

like image 726
SNag Avatar asked Aug 06 '13 08:08

SNag


People also ask

How do you create an empty array of a certain length?

The first way of creating an empty array of specific lengths is by using the Array() constructor and passing an integer as an argument to it. Since we are calling a constructor, we will be using the new keyword.

How do you declare an empty array in VBA?

Use a Static, Dim, Private, or Public statement to declare an array, leaving the parentheses empty, as shown in the following example. Use the ReDim statement to declare an array implicitly within a procedure. Be careful not to misspell the name of the array when you use the ReDim statement.

What is the best way to initialize an array in Visual Basic?

To initialize an array variable by using an array literalEither in the New clause, or when you assign the array value, supply the element values inside braces ( {} ). The following example shows several ways to declare, create, and initialize a variable to contain an array that has elements of type Char .

How do you declare an array in Visual Basic?

In visual basic, Arrays can be declared by specifying the type of elements followed by the brackets () like as shown below. Dim array_name As [Data_Type](); Here, array_name represents the name of an array and Data_type will represent the data type of elements to store in an array.


1 Answers

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) {} 
like image 144
Abbas Amiri Avatar answered Sep 21 '22 08:09

Abbas Amiri