Game Development Reference
In-Depth Information
defines what happens when we retrieve data from an object, and what happens when
we assign a value to data inside an object. So, let us now add a property for getting
and setting the color of the cannon object.
7.4.4 Retrieving the Color of the Cannon Object
Adding a property to a class is actually quite similar to adding a method, but a prop-
erty has a slightly different header and body. In the header of a property, we need
to indicate what the type is of the data that the property accesses. We also have to
provide a name, just like with a method. For accessing the color of a Cannon object,
we need a property of type Color , and we will call this property Color . Although the
name of the property happens to be the same as its type, this is not a problem for the
compiler. Similarly, the property GraphicsDevice from the Game class also carries the
name of the type of data that it controls (which is an object of type GraphicsDevice ).
Generally, it is better to choose another name for the property, but in some cases it
makes sense, especially when the object involved only has one thing of that type. In
these examples, a game will have only one graphics device, and a cannon will have
only one color at a time. The header of the Color property is given as follows:
public Color Color
An important difference between methods and properties, is that properties can con-
sist of a get part and a set part. The get part contains the instructions to retrieve the
data, and the set part contains the instructions for modifying the data. Not every
property contains both a get and a set part. If a property only contains a get part, it
is called a read-only property, meaning that we cannot use the property to modify
the data, only read it.
The get part of a property is indicated by the keyword get , followed by a sequence
of instructions placed between braces. Just as for a method that has a return value,
we use the return keyword to indicate what value the property should return. In this
case, we want to return the data contained in the member variable color . So, the Color
property is given as follows:
public Color Color
{
get { return color; }
}
We can now use this property to access the color of the cannon. For example, we
can store it in a variable, like this:
Color cannonColor = cannon.Color;
Search WWH ::




Custom Search