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

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 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) {}

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)

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

Related

VBA user-defined-datatype array to range

I have a public variant array populated with a range containing several data types (dates, numbers, strings, booleans...)
I have functions taking those types as parameter and works on the "columns" of my array.
Each function have been tested by passing them directly variable (not arrays) and worked fine.
But when the program tries to compile, it returns me an error : "argument Type Byref not compatible". To me, I don't declare things how i should. Any advice would be welcome.
Dim myArray() As Variant
myArray = importedRange.Value
myArray (12) = aFunction(myArray (3))
Edit :
I the public variant array is no more. I replaced it with an array of a new private type composed of the types I needed. It works perfectly.
In order to fill this array I copy data from ranges using "For" loops (for a test purpose but i'm open to any upgrade).
I wonder now if there is a way to copy my new array in a given range avoiding using more loops.
This line worked for my first variant array but doesent with the new one.
Dim zoneStockage As Range
Set zoneStockage = Sheets("Archive_Test").Range("A1")
Dim tableauFactures(3) As Facture
'allocating my new array.
(I've skipped this code because there are 18 parameters composing it.)
zoneStockage.Resize(UBound(tableauFactures, 1), 18).Value = tableauFactures
Thanks for your help.
It's ugly, maybe not more effective than using "sheets.range" but it works anyway:
For i = 0 To 5
With myUDT(i)
.Name = Sheets("a").Range("A" & i)
.Color = Sheets("a").Range("B" & i)
.dateCreation = Sheets("a").Range("C" & i)
.dateDebutContrat = Sheets("a").Range("D" & i)
End With
Next i

Type casting Strings

I am using an array list to store my strings. However when I run the program it throws an error : Conversion from type 'String()' to type 'String" is not valid. I am sure I am missing something simple. I thought an ArrayList was a list of objects and that it could be anything that I was sent to the array. e.g. Strings in, Strings out. Here is the code that I am working with.
Dim tempString As New ArrayList()
For Each s As String In tempString
Dim sAry As String() = bufString.Split(New Char() {ChrW(2)})
For i As Int16 = 1 To sAry.Length
xlCells(CurrentRow, i).Value = sAry(i - 1).ToString()
Next
Next
I also have come to understand that ArrayList has depreciated, should I be using something else?
Before jumping into your case quickly please give a look into other great answers
What's Wrong with an ArrayList?
.NET: ArrayList vs List
and you can google to know more in this regard...
For known typed collection it is not good to use ArrayLists.
For your case I would suggest generic List collection(List is much more efficient in terms of memory usage)
You can see my below test case for you:
Sub Main()
Dim tempList As New List(Of String) 'Consider List Rather ArrayList as you knw your requirement for Strings collection
tempList.Add("string1string2string3string4") 'for testing purpose I've joined "string1, string2, string3 & string4" with ChrW(2) unicode character
For Each s As String In tempList
Dim sAry As String() = s.Split(New Char() {ChrW(2)})
For i As Int16 = 1 To sAry.Length
'xlCells(CurrentRow, i).Value = sAry(i - 1).ToString()
Console.WriteLine(sAry(i - 1).ToString())
Next
Next
Console.ReadLine()
End Sub

How can I iterate through an array of strings using VB?

Here's my code so far:
Dim i As Integer
Dim stringArray() as String
stringArray = split("Hello|there", "|")
For i = 0 To stringArray.Length()
' Logic goes here
Next
VB6 doesn't seem to like me using stringAray.Length() and gives me a compile error message like Invalid Qualifier, but what's the right way to iterate through each element of a string array?
ubound() returns the upper bounds;
Dim i As Long
Dim stringArray(1) as String
stringArray(0) = "hello"
stringArray(1) = "world"
For i = 0 To ubound(stringArray)
msgbox(stringArray(i))
Next
Dim i As Integer
Dim stringArray() as String
stringArray = split("Hello|there", "|")
For i = 0 To ubound(stringArray)
' Logic goes here
Next
This is the coding for above questions.
I have re do and also include the output using Visual Basic 6.0
it is pretty simple and easy to understand.
However,I wanted to try for more iteration.
click here for the coding and the output

My arrays are resizing on the fly

If I do Dim array As String() I seem to be able to resize that array and put anything in it on the fly. For example:
Dim PackUrls As String()
PackUrls = Split(WebRequest("http://" + sPackBaseURI, sPackBaseURIUsername, sPackBaseURIPassword), ":")
And I don't get an error and nothing weird is happening with the array.
I did this without thinking THEN i read that you have to specify the size of the array first! Why is this happening?
This is what is happening in your code
'Create an empty string array called PackUrls
Dim PackUrls As String()
'Create a new string array from the Split function
'and assign it to the variable PackUrls, replacing the old value.
PackUrls = Split(WebRequest("http://" + sPackBaseURI, _
sPackBaseURIUsername, sPackBaseURIPassword), ":")
There is no copying from the result of Split to PackUrls. The original content (which is nothing by the way) is replaced with the new content from Split. Therefore there is no need to resize the array. You could easily rewrite your code like this and it would work:
Dim PackUrls As String() = Split(WebRequest("http://" + sPackBaseURI, _
sPackBaseURIUsername, sPackBaseURIPassword), ":")
When you assign and array to var you are replacing it with the new array, no matter the size. The var now is pointing to a new data of the same type, so no error is needed.
When you assing a array to an array var you are not copying the items individually, but the variable is poiting to the new array.

How to assign a set of text values to a string array?

How can I assign a set of text values to an array? Nothing I tried is working!
Months = Array("Jan", "Feb", ..., "Dec")
and others I tried do not work!
Here's something about VB: http://www.devx.com/vb2themax/Tip/18322
Visual Basic doesn't provide any way
to declare an array and initialize its
elements at the same time. In most
cases you end up with setting
individual elements one by one, as in:
Dim strArray(0 To 3) As String
strArray(0) = "Spring"
strArray(1) = "Summer"
strArray(2) = "Fall"
strArray(3) = "Winter"
Under VB4, VB5, and VB6 you can create
an array of Variants on the fly, using
the Array() function:
Dim varArray() As Variant
varArray() = Array("Spring", "Summer", "Fall", "Winter")
but there is no similar function to
create arrays of data types other than
Variant. If you're using VB6, however,
you can create String arrays using the
Split() function:
Dim varArray() As String
' arrays returned by Split are always zero-based
varArray() = Split("Spring;Summer;Fall;Winter", ";")
I'm pretty sure you can only do it like this:
dim months(2) as string
months(0) = "Jan"
months(1) = "Feb"
months(2) = "Mar"
If you're talking about vbscript then this works:
months = Array("may","june","july")
If it's vb.net then:
dim months() as string = {"may","june","july"}

Resources