RSilva RSilva - 4 months ago 13
Vb.net Question

Change item value in a list of object vb.net, doing a for-next

Given the class...

Public Class Method
Public Property Sequence as integer
End class


and the next function

Public shared function SetMethod(Methods as List(of Method))
Dim i as integer

For i = 0 To (Methods.Count - 1)
Methods(i).Sequence = i
next i

End function


... why is that this functions always changes all items in the list of Methods? For example, if methods.count = 10, why all methods.Sequence will have the value 10?

How can I make all items have a different value?

Answer

The code should work as it is. But i think you have assigned always the same object to the list instead of ten different.

So something like this:

Dim methods as New List(Of Method)
Dim m1 As New Method()
For i As Int32 = 1 To 10 
    methods.Add(m1)
Next

Change it to:

Dim methods as New List(Of Method)
For i As Int32 = 1 To 10 
    Dim m1 As New Method()
    methods.Add(m1)
Next

The first approach will add the same object ten times to the list. So by modifying one you will modify all. The second approach will actually create ten different objects and is the correct way.

Side-note:

The first approach will actually add the reference to m1 ten times to the list since all classes are reference types. It is was a value type it would create "copies". So if you'd modify class Method to be a Structure it would "work".

Debug.Assert(ReferenceEquals(methods(0),methods(1)))

This is never true if Method was a Structure(a value type) but always if it's the same reference as it seems to be in your case. But that's not a suggestion to use structs instead of classes. It should just show you the difference of reference- and value types.

Comments