Game Development Reference
In-Depth Information
And now the following instructions:
float
someNumber = 10.0f;
Square(someNumber);
After executing these instructions the value of
someNumber
still is
10.0f
(and not
100.0f
). Why is this? It is because when the
Square
method is called, the
float
pa-
rameter is passed
by value
. The variable
f
is a local variable inside the method that
initially contains the value of the
someNumber
variable. Inside the method, the local
variable
f
is changed to contain
f
f
, but this does not change the
someNumber
vari-
able, because it is another location in memory. Because class objects are passed by
reference
, the following example will change the object's color:
∗
void
ChangeColor(Cannon cannon)
{
cannon.Color = Color.Red;
}
...
Cannon cannon1 =
new
Cannon(cannonSprite);
ChangeColor(cannon1);
// The object referred to by cannon1 now has a red color.
7.6.2 The
null
Keyword
So if variables whose type is a class contain references to objects, instead of direct
values, what happens when we declare a variable of that type? Suppose that we
declare a member variable of type
Cannon
:
Cannon anotherCannon;
At this point, we have not yet created an object (using the
new
keyword) that this
variable points to. So what does the memory look like? It looks like this:
The variable is not yet pointing to anything. We indicate this with the keyword
null
. It is even possible to check in a C# program whether a variable is pointing to
an object or not, like this:
if
(anotherCannon ==
null
)
anotherCannon =
new
Cannon(cannonSprite);
In this example, we check if the variable is equal to
null
(not pointing to an object).
Ifso,wecreatea
Cannon
instance using the
new
keyword. After that, the memory
looks like this: