wayofthefuture
wayofthefuture

Reputation: 9405

Properly storing objects in array

I know this is probably a dumb question, but it's a really big deal so I want to make sure I do it properly. Is this okay?

Dim obj as MyObj
Dim objarr as New Arraylist

For x as Integer = 1 to 10
     obj = New MyObj
     obj.SomeValue = x
     objarr.add(obj)
Next

Will the array contain all separate objects or will they all contain the same object? Am I making mistakes by using the same MyObj object to add to the list? Thanks

Upvotes: 2

Views: 1660

Answers (4)

Steven Doggart
Steven Doggart

Reputation: 43743

Yes, your code will work fine. Each time you use the New operate you instantiate (create) a new object. Therefore, each time through the loop, the obj variable will be re-assigned to reference a new object.

There are a couple of things, though, about your code which could be improved. First, you should use List(Of MyObj) rather than ArrayList. Second, it would be less confusing if you simply declared the obj variable inside of the loop, for instance:

Dim objects As New List(Of MyObj)()
For x As Integer = 1 To 10
    Dim obj As New MyObj()
    obj.SomeValue = x
    objects.Add(obj)
Next

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

10 Different Objects:

Dim obj(9) as MyObj
Dim objarr New Generic.List(Of MyObj) 'As Neolisk Suggested in Original Post

For x as Integer = 0 to 9
     obj(x).SomeValue = x
     objarr.add(obj(x))
Next

10 Different Instances of a same object:

'-------Your Code------
Dim obj as MyObj
Dim objarr as New Arraylist

For x as Integer = 1 to 10
     obj = New MyObj
     obj.SomeValue = x
     objarr.add(obj)
Next

Upvotes: 0

Dmitriy Khaykin
Dmitriy Khaykin

Reputation: 5258

You are only reusing the MyObj variable - think of it as a container. Each time you call this line

obj = New MyObj

You are creating a new instance of MyObj; therefore, your ArrayList will contain 10 different instances of MyObj.

Upvotes: 1

Victor Zakharov
Victor Zakharov

Reputation: 26424

You usually declare a collecting list outside of your loop. My take on it:

Dim objarr as New Generic.List(Of MyObj)
For x as Integer = 1 to 10
  objarr.add(New MyObj With {.SomeValue = x})
Next

And here is a class I used for testing purposes:

Private Class MyObj
  Public Property SomeValue As Integer
End Class

Upvotes: 2

Related Questions