Game Development Reference
In-Depth Information
We also want to be able to assign a value to the cannon color. For that, we have to
define the
set
part of the property. In that part, we need to modify the value of the
color
variable. This value is provided when the property is used in another method.
For example, it could be an instruction like this:
cannon.Color = Color.Red;
So how do we access the right-hand side of this assignment in the property? This
is done with the
value
keyword. Therefore, we can write down the
set
part of this
property as follows:
set
{ color =
value
;}
But when we set the color of the cannon, we also have to change the current color
indicator sprite. For that, we have to first check what the new color is, and based
on that we change the
currentColor
variable. So, the complete
Color
property is then
given as follows:
public
Color Color
{
get
{
return
color; }
set
{
color =
value
;
if
(color == Color.Red)
currentColor = colorRed;
else if
(color == Color.Green)
currentColor = colorGreen;
else if
(color == Color.Blue)
currentColor = colorBlue;
}
}
Now, suppose that someone would use the class, and do the following:
cannon.Color = Color.Black;
What would happen? Not much actually. Because of the conditions in the
if
instruc-
tion, the
currentColor
variable would not change. But the
color
variable would contain
the value
Color.Black
. So, the cannon object will now be
inconsistent
. Although this
will not lead to immediate problems in this case, it is better to avoid these kinds
of inconsistency. But what stops other users of the
Cannon
class from assigning
incorrect colors? Well, nothing. Of course, you could periodically contact all the
programmers in the world that use your
Cannon
class and verify that they assign the
right color to the cannon instances, but that would be a lot of work. A better way
would be to program the properties to make sure that the object remains consistent.
For example, we can make a more secure version of the
Color
property by modifying
the
set
part as follows: