Game Development Reference
In-Depth Information
Cannon cannon1;
cannon1 =
new
Cannon(cannonSprite);
Cannon cannon2 = cannon1;
Looking at the example using the
int
type, you would expect that there are now two
cannon objects in the memory: one stored in the variable
cannon1
, and one stored in
cannon2
. However, this is not the case! Actually, both
cannon1
and
cannon2
refer to
the same object
. After the first instruction (creating the
Cannon
object), the memory
looks like this:
Here, you see that there is a big difference between how a basic type such as
int
or
float
is represented in memory and more complicated types such as the
Cannon
class. In C#, all objects of a class type are stored as
references
as opposed to values.
This means that a variable such as
cannon1
does not directly contain the
Cannon
object, but it contains a reference to it. If we now declare the
cannon2
variable and
we assign the value of
cannon1
to it, the memory looks like this:
The result is that if we would change the color of the cannon as follows:
cannon2.Color = Color.Red;
then the expression
cannon1.Color
would be
Color.Red
, since both
cannon1
and
cannon2
refer to the same object! This also has an effect on how objects are passed
around in methods. For example, in the
Draw
method of the
Cannon
class, we pass
a
SpriteBatch
object as a parameter. Because
SpriteBatch
is a class, we pass this pa-
rameter as a
reference
. The result of this is that we can
change
the
SpriteBatch
object
in our method (for example, by drawing in it). Passing basic types such as
float
as
parameters to method happens
by value
, so changing the value inside the method
has no effect. Consider the following method:
void
Square(
float
f)
{
∗
f;
f=f
}