0

I've got the following:

For Each curCustomer As Customer In _customersEdit
    If (IsNothing(curCustomer)) Then
        Continue For
    End If
    'other code
    If (curCustomer.SeatIDs(0) = primarySeat) Then
        'other code
    End If

    If (curCustomer.SeatIDs.Count = 0) Then
        curCustomer = Nothing
    End If
Next

After running this code once it's fine, when you run it the second time though I get an error on checking if it's a primary seat because SeatIDs is Nothing. When I set a breakpoint on curCustomer = Nothing it triggered the first time around, I changed the customers name to "test", put a breakpoint on the next line and it did set curCustomer to nothing like it should have. Next when I ran the code again it threw the error on checking the primary seat, and curCustomer still existed with the "test" name I gave it before setting it to Nothing. Why is this happening?

Levi H
  • 3,426
  • 7
  • 30
  • 43
  • It is difficult for me to understand what you are trying to do. You are changing the local variable reference that is rebound each iteration. – strmstn Oct 23 '12 at 18:20
  • I'm trying to set curCustomer to Nothing in _customersEdit. If it's a reference then surely setting it to Nothing will set it to nothing in the array? – Levi H Oct 23 '12 at 18:26
  • No, at the top of the loop there are 2 different references to the same object, one in `curCustomer` and one in `_customersEdit(i)`. Setting `curCustomer` to `Nothing` only affects that variable, not the array. – Tom Smilack Oct 23 '12 at 18:30
  • Ahh, I didn't know setting it to nothing set it's reference to nothing and didn't set what the object it references to nothing, thanks. – Levi H Oct 23 '12 at 18:37

2 Answers2

2

The curCustomer = Nothing isn't actually doing anything (in the example) as curCustomer is re-initalized in the next for-each sequence and curCustomer function only as a reference (you are nulling the reference to the item in the array, not the array item itself).

You will need to use an index to set it to nothing in the array _customersEdit.

You could do:

    Dim i As Integer
    For i = 0 To _customersEdit.Count - 1
        ' your check code
        If (curCustomer.SeatIDs.Count = 0) Then
            _customerEdit(i) = Nothing
        End If

    Next

Or probably better:

    Dim i As Integer
    For i =  _customersEdit.Count - 1 To 0 Step -1
        ' your check code
        If (curCustomer.SeatIDs.Count = 0) Then
            _customerEdit.RemoveAt(i)
        End If
    Next
0

_customersEdit(i) = Nothing will set the reference in the array to Nothing.

strmstn
  • 852
  • 6
  • 10