3

I am having a problem when setting VB.NET list object to another. In the example below I create an instance on ReadLocations and than create an object of ReadLocation where then I loop through ReadLocations and set ReadLocation1 equal to rl.

What happens is that if I then go and change ReadLocation1 to something else (assdfhsd) it will also change the ReadLocations index. I am really confused why it would be doing that unless it is "=" sign means referencing instead of actually setting the value. Please help as I am a C# developer but the program I am modifying is in VB.NET.

Dim ReadLocations As New List(Of Model.ReadLocation)
Dim rl1 As New Model.ReadLocation
rl1.LL = "a"
Dim rl2 As New Model.ReadLocation
rl2.LL = "b"
ReadLocations.Add(rl1)
ReadLocations.Add(rl2)

Dim ReadLocation11 As New Model.ReadLocation

For Each rl As Model.ReadLocation In ReadLocations
    ReadLocation11 = rl
Next
3
  • What is ReadLocation1? Is ReadLocation11 a typo? Commented Jun 15, 2012 at 14:31
  • What do you mean with: 'it will change the ReadLocations index'? Commented Jun 15, 2012 at 14:32
  • ReadLocation1 is a Model.ReadLocation which a class. What i Mean by ReadLocations index is if I change the ReadLocation1 (not a typo) it changes the value for the same object inside ReadLocations. Commented Jun 15, 2012 at 16:08

1 Answer 1

6

If ReadLocation is a reference type (a Class), then all variables set to instances of objects of that class will always be references. The = operator only ever sets a new reference to an object when it is operating on reference types. It will never make a clone of the object (unless it is a value type). The same is true in C#. The only way to do what you want to do, would be to clone the objects when you add them to the second list. Unfortunately, .NET doesn't provide a simple automatic method for cloning any object. The standard way to do this would be to implement the ICloneable interface in your ReadLocation class. Then you could clone it by calling the clone method:

ReadLocation1 = CType(rl.Clone(), ReadLocation)

However, inside that clone method, you will need to create a new instance of ReadLocation and manually set all of its properties and then return it. For example:

Public Class ReadLocation
    Implements ICloneable

    Public Function Clone() As Object Implements ICloneable.Clone
        Dim clone As New ReadLocation()
        clone.Property1 = Me.Property1
        clone.Property2 = Me.Property2
        Return clone
    End Function
Sign up to request clarification or add additional context in comments.

Comments

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.