Jordan Trainor
Jordan Trainor

Reputation: 2438

Variable changing...another variable?

enter code here`I have a variable called curPos that stores two ints. I have a second variable prevPos that stores two ints.

So I have the following code

Console.WriteLine("{0}, {1}", curPos[0], curPos[1]); // 1, 25
Console.WriteLine("{0}, {1}", prevPos[0], prevPos[1]); // 1, 25
                    curPos[0]++;

Console.WriteLine("{0}, {1}", curPos[0], curPos[1]); // 2, 25
Console.WriteLine("{0}, {1}", prevPos[0], prevPos[1]); // 2, 25

how is this even possible and this is the exact code when I step line by line to the last line shown http://www.youtube.com/watch?v=qkPKm7xEhac&feature=youtu.be

Upvotes: 1

Views: 117

Answers (2)

Rune FS
Rune FS

Reputation: 21742

They might be two different variables but they are pointing to the same object.

A variable is a compile time construct that gives a name to a storage location. At runtime that storage location is what we generally refer to as an object.

if you say

var foo = int[]{0,1};
var bar = foo;

you have one array that you can access through two variables. It subsequently does not matter whether you do

foo[0]++;

or you type

bar[00]++;

the result is the same. The first integer in the array is incremented by one.

This holds true as long as the type of the variables is a reference type such as an array. If the type of the variables is a Value type such as int or Point then any assignment will create a copy

Point foo = new Point();
var bar = foo;

in this case bar and foo does not point to the same object

Upvotes: 2

juharr
juharr

Reputation: 32266

Both variables are pointing at the same array. My guess is at some point in your code you have something like:

prevPos = curPos

When what you really want is

prevPos[0] = curPos[0]
prevPos[1] = curPos[1]

Upvotes: 4

Related Questions