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 Answers 2

4
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).

Sign up to request clarification or add additional context in comments.

1 Comment

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.)
2

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.

3 Comments

Yeah, my VB.NET is a bit rusty it seems. Updated the answer now.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.