I am relatively new to programming and am having trouble wrapping my head around how a class holds its data.
I have a simple class (Boardstate) which holds an array of blocks (another class) and a collection of possible moves.
I declare a new instance of Boardstate, initialise it with some data and then add it to a collection of BoardStates.
Later in the code I retrieve this Boardstate and assign it to a temporary board. I then call a public function (from the temp board) which applies one of the the possible moves to the board and returns the result.
I then add this result to my collection of Boardstates.
The issue i have is that when I manipulate data in the temporary board (a new instance of the class), every previous instance is being changed. I believe I must be using incorrect syntax to copy the class, which is resulting in some kind of link.
Here is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim thisBoard As New BoardState
thisBoard.AddBlock(1, 1, 1, 1, 2)
thisBoard.AddBlock(2, 2, 2, 2, 2)
thisBoard.AddBlock(3, 1, 3, 1, 3)
thisBoard.AddBlock(4, 2, 3, 3, 3)
thisBoard.AddBlock(5, 3, 1, 3, 2)
thisBoard.AddBlock(6, 3, 5, 4, 5)
thisBoard.AddBlock(7, 1, 4, 2, 5)
thisBoard.AddBlock(8, 4, 1, 4, 1)
This part is fine - initiates the board and adds it to the global(!) collection, BoardTrail.
Later in my code I have:
Dim tempBoard As New BoardState
Dim compBoard As New BoardState
tempBoard = BoardTrail(1)
compBoard = tempBoard.Move()
If I explore the BoardTrail collection, it shows that BoardTrail(1) has had the Move function applied to it.
I have experimented, and even adding another block to a different instance (compBoard.AddBlock(someblockdata)) is reflected in BoardTrail(1).
The Move function *does* change the contents of the boardstate it is called from, ie after tempboard.move(), tempboard has had a move applied to it. (I know, not good practise...) But why does this change BoardTrail(1)?
Am I missing the point of the '=' assignment when it is applied to an instance of a class - it seems to form a rather strong bond between the two instances?
Is there a way I can copy the elements stored in a class to a new instance of it, without having to resort to making everything in it public and copying it over, or declaring a pile of read only properties?
Any help is greatly appreciated!