When I assign x = y and then later change x, y is getting changed

My subject line is a simplistic summary of my real problem. I am a new programmer to Visual Basic, with prior experience in main frame structured programming in PL/I, so I have not tried to use the object oriented principles in my first program. Here is the pertinent parts of the code where I have problems:

Public Class Form1

Structure SudokuBox

Dim Answer As String

Dim NumPossible As Integer

Dim Square As Integer

Dim Possibles As String

End Structure

Dim ScreenArray(8, 8) As SudokuBox

Dim SaveArray(8, 8) As SudokuBox

Etc

Private Sub TryAPossibility()

SaveArray = ScreenArray

Call GetPossibile()

Etc

End Sub

Private Sub GetPossibile()

Dim i As Integer

Dim j As Integer

Dim TryAnswer As String

etc

TryAnswer = ScreenArray(i, j).Possibles.Substring(0, 1)

ScreenArray(i, j).Answer = TryAnswer

End Sub

I have in effect declared two arrays as global variables (using my old terminology from PL/I). Up until the point where I assign the ScreenArray to SavedArray, I can see, using debug, the SaveArray has 0 for integers and nothing for the strings. But after that, when I assign TryAnswer to ScreenArray, using debug, I can see it is assigned to SaveArray too. And in fact, whenever I assign anything to ScreenArray, it then gets assigned to SaveArray.

WHY



Answer this question

When I assign x = y and then later change x, y is getting changed

  • Jason Beheler

    Yeah, it's a handy method because if Possibles = 111111111 and Solved = 000000010, then by using Boolean arithmetic:

    Possibles And (Not Solved) = UpdatedPossibles

    UpdatedPossibles = 111111101


    David.

  • nanci ruhl

    Yes, I thought about it, but not until after I had coded the program using a string <smile>
  • Todd Hobdey

    Confuscious say, "In all things, balance"

  • Vinay Kittur

    Hi Greenhorn,

    Have you considered storing the "Possibles" in your Sudoku program as a single binary number where the 9 most significant bits indicate whether a possibility is "on" or "off" e.g 100000011 would indicate that the possibles are 9,2 and 1.

    David.

  • RickRSL

    Thank you. That was the answer. I guess I need to do more reading, and less jumping in and coding, although it is not as much fun.
  • lauramc

    This is the behavior you get with classes (aka reference types). The assignment SaveArray = ScreenArray only copies an object reference, so you now have two variables referencing the same object in memory. That's why the effects of changing it through one variable can be seen when accessed through another. Arrays are always reference types so there's not much you can do about it other than to manually clone the array.



  • When I assign x = y and then later change x, y is getting changed