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.
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.
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.
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 .
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.
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) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With