user1625159
user1625159

Reputation: 45

Initialise array using Array.ForEach - VB.NET

I have an array of RichTextBoxes and I would like to initialise them using Array.ForEach.

I have made the following attempt with no success:

Dim aRTB(5) as RichTextBox
Array.ForEach(aRTB, Function() New RichTextBox)

This code was the only one to make it past the compiler however it doesn't initialise any part of the array.

Code which failed to past the compiler includes:

Array.ForEach(aRTB, Function() Return New RichTextBox)
Array.ForEach(aRTB, Function(rtb as RichTextBox) rtb = New RichTextBox)

I realise I could easily set up a a regular loop (For, Do, While) to perform the same action however I would like to see if this way can work.

Thank you for any help.

Upvotes: 1

Views: 5802

Answers (1)

Heinzi
Heinzi

Reputation: 172230

I have an array of RichTextBoxes and I would like to initialise them using Array.ForEach.

You cannot. Array.ForEach performs an action on every element of the array, i.e., it passes the elements of the array to your function a parameter:

Array.ForEach(aRTB, Sub(rtb as RichTextBox) ...do something with rtb...)

The parameter is ByVal, i.e., you cannot use this to change the contents of the array:

Array.ForEach(aRTB, Sub(ByRef rtb as RichTextBox) rtb = New RichTextBox())
' Yields compilation error: 
' Nested sub does not have a signature that is compatible 
' with delegate 'System.Action(Of RichTextBox)

Since your array is initially empty, you can't do anything useful with Array.ForEach on it.

Sorry, but you will have to use a classic For loop for this:

For i = 0 To 5
    aRTB(i) = New RichTextBox()
Next

The 0 To 5 is not a typo... in VB.NET array declarations specify the upper bound, not the size.

Upvotes: 2

Related Questions