views:

281

answers:

2

What is the VB.NET syntax for declaring the size of an array of objects at runtime?

To get an idea of what I mean, here is the code so far:

Private PipeServerThread As Thread()

Public Sub StartPipeServer(NumberOfThreads As Integer)
    ' ??? equivalent of C#
    ' ???   PipeServerThread = new Thread[numberOfThreads];
    ' ??? goes here
    For i = 0 To NumberOfThreads - 1
        PipeServerThread(i) = New Thread(New ThreadStart(AddressOf ListeningThread))
        PipeServerThread(i).Start()
    Next i
End Sub

I've tried several things but just end up conflating it with object creation syntax.

+2  A: 

This should be what you want:

ReDim PipeServerThread(numberOfThreads - 1)

You can't use the New keyword, since the VB.NET compiler interprets this as an attempt to create a new instance of the type Thread.

Noldorin
Yeah, my VB.NET is a bit rusty it seems. Updated the answer now.
Noldorin
Deleted my previous comment as it didn't make sense with the edit :)
@Noldorin: it's not equivalent to the C# statement mentioned. See my answer.
Mehrdad Afshari
+4  A: 
PipeServerThread = New Thread(numberOfThreads - 1) { }

Alternatively:

ReDim PipeServerThread(numberOfThreads - 1)

Remember that the value inside parenthesis is the upper bound of the array in VB.NET (unlike C# where it's array length).

Mehrdad Afshari
Many thanks for that, just what I needed.
The "upper bound" of the array is the correct term for what you specify between the brackets, but yes, this is right. It is however slightly annoying that VB.NET and C# differ in this respect. (The C# way seems much more logical.)
Noldorin