Classes and append

Hello good people,
I create a class named Vehicle, and it has two properties: Brand and Model. I’m trying to save data in this ‘Cars’ array, but often only a few properties change, like this:

Dim Cars(-1) As Vehicle

//first car
Dim car As New Vehicle
car.Brand="Ford"
car.Model="Focus"

//save first car
Cars.Append(car)

//second car, same brand
car.Model="Fusion"

//save second car 
Cars.Append(car)

I would expect that Cars(0).Model=“Focus” and Cars(1).Model=“Fusion” , but both values are equal to “Fusion” . If both were the first value “Focus” I’d probably be conviced that this is how life works, but Cars(0).Model=“Fusion” doesn’t make sense for me. Didn’t I just save the first car with append?

The problem is here, try to do:

[code]Dim car1 As New Vehicle
car1.Brand=“Ford”
car1.Model=“Fusion”

//save second car
Cars.Append(car1)[/code]

car is a “reference” appended to array, if you change something, that change is made in the array ítem.

Hello Lucas,

You’ve saved a reference to the car instance inside the Array; so, if you modify the instance with a new value for any of his properties… then you’re modifying also the reference. I mean, as listed by the example, your array has two entries pointing to the same instance.

If you want to put two different instances in the array, then you have to use two variables of type Vehicle:

Dim car1 As New Vehicle
Dim car2 As New Vehicle

Javier

You created an object and assigned it to a variable , car. Then you appended that same object to the array twice.

Try this:

// second car
car = new Vehicle
car.Brand = "Ford"
car.Model = "Fusion"

Cars.Append car

To make this easier, you can define a “copy” Constructor in Vehicle like this:

Sub Constructor()
  // No params
End Sub

Sub Constructor (copyFrom As Vehicle)
  Brand  = copyFrom.Brand
  Model = copyFrom.Model
End Sub

Later. In your example, you can do this:

dim template as new Vehicle
template.Brand = "Ford"

dim car as new Vehicle( template )
car.Model = "Focus"
Cars.Append car

car = new Vehicle( template )
car.Model = "Fusion"
Cars.Append car

but you’ve only created 1 “new” vehicle, so any changes you make to car will be what that 1 vehicle contains.
I would probably do this.
Create a Constructor method for vehicle taking the args “brand” and “model”
now…

[code]dim car as new Vehicle(“Ford”, “Fusion”)
Cars.append car

car = new vehicle(“Ford”, “Focus”)
cars.append car[/code]

etc…

Thanks, I was saving a reference to the car instance inside the Array, important information here hehe.
In my project there’s a couple properties, so I’d like not to redefine all of them, sounds like Kem gave me a clean solution.
Thank you all!