kdonah3
kdonah3

Reputation: 155

Why does List.Clear() also get rid of a class property?

I have the following class:

    Public Class ID
        Private sID as List(Of Integer)

        Public property IDlist as List(Of Integer)
            Get
                Return sID
            End Get
            Set(ByVal value as List(Of Integer)
                sID = value
            End Set
        End Property
    End Class

I then do:

    Dim objID as ID
    Dim myList as List(Of Integer)

    for i = 0 to 1
        objID = New ID
        MyList.add(1)
        Mylist.add(2)

        ID.IDlist = mylist
        mylist.clear
    Next

If I insert code to retrieve one of the ID.IDlist properties BEFORE mylist.clear it works fine for both iterations. However, if I try to retrieve the values AFTER the for loop I get nothing.

I found that this code allows me to get the ID.IDlist for both ID objects after for for loop:

    Dim objID as ID
    Dim myList as List(Of Integer)

    for i = 0 to 1
        objID = New ID
        mylist = New List(Of Integer)

        MyList.add(1)
        Mylist.add(2)

        ID.IDlist = mylist
    Next

I could be way off here, but it almost seems like ID.IDlist points to the address of mylist and so when mylist is cleared so is ID.Idlist. It seems as though the reason the second block of code works is because I am creating a new list in memory for each ID object and ID.IDlist just points to it... is that right?

Can anyone confirm / explain? I spent like 5 hours on this situation.. ugh

thank you for any explanation!

Upvotes: 0

Views: 1829

Answers (2)

the_lotus
the_lotus

Reputation: 12748

When you do: ID.IDlist = mylist

Both ID.IDlist and mylist are the exact same list. If you clear one, you also clear the other.

Also, I don't think this will compile since ID is a class and not an object.

Upvotes: 1

chrissie1
chrissie1

Reputation: 5029

Yes you are passing a reference type which means that you are creating a copy of the pointer to the object in the stack.

To prevent this you can make a shallow copy of the list. In this case that would be easy by using the Extension method ToList().

objId.IDlist = myList.ToList()

Upvotes: 2

Related Questions