3

I'm using an array of class; the class is very simple and only contains one element. The class is declared as follows:

Class Cell
    Public Info As Int16
End Class

The array:

Dim Maze(11, 15) As Cell

I want to use a simple sub to set the .Info variable for every element to 15, but I realise I have to create the elements first. I tried using a For Each loop as follows, but it didn't work, when the loop completed everything was still set to nothing:

For Each e As Cell In Maze
    If e Is Nothing Then
        e = New Cell
    End If
Next

I'm not concerned about the correct solution: I used a regular For loop and this accomplishes everything I want done...

For a = 0 To Maze.GetUpperBound(0)
    For b = 0 To Maze.GetUpperBound(1)
        Maze(a, b) = New Cell
        Maze(a, b).Info = Maze(a, b).Info Or 15
    Next
Next

...but I'd like to know why the For Each loop didn't work in the first place, as I'm sure there's some fundamental principle I'm missing here.

2
  • 1
    In a for each loop you cannot affect the variable being iterated. VB.NET shouldn't allow you to write this code; although banning is not the VB.NET style :) Commented Jul 19, 2013 at 18:48
  • Ahh okay. Maybe VB.net is a bit too permissive... Commented Jul 19, 2013 at 22:11

1 Answer 1

6

The reason the For Each loop did not work is because within the For Each construct, the local variable (in your case e) is not a reference, but rather a copy; thus your New Cell has no consequence on your array of Cell.

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

4 Comments

Actually, this is one of the consequences from VB.NET being so permissive. C# does not allow this configuration. Being permissive is fine but some times might be confusing for the programmer; in this case is logical assuming that the value of e is actually being changed.
Great point @varocarbas - I did not realize that C# did not even allow it until I just tried it in code.
Oh wow, I had never realised. Thank you! I've probably made this mistake many times before.
@LeoKing - If you feel this answer was helpful, then feel free to accept the answer. Good luck to you.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.