Game Development Reference
In-Depth Information
•
The
==
operator is redefined and does the same as the
Equals
method. This is a
smart move: without this redefinition, the
==
operator would compare the refer-
ences and not the content of the objects. There are situations where two
string
references to different object contain the same value. Thanks to the redefinition
the comparison will then still yield
true
. In languages such as Java and C this is
not done, so you have to watch out when you are comparing strings.
With the
SubString
method you can select a part of the string, for example the first
five characters:
string
head;
head = s.SubString(0,5);
The numbering of the positions in a string is—just like arrays and lists—a bit spe-
cial: the first character is position 0, the second character position 1, and so on. As
parameters to the
SubString
method, you provide the position of the first character
that you need, and the position of the first character that you do not want anymore.
Therefore, the call
s.SubString(0,5)
gives the characters at positions 0, 1, 2, 3, and 4;
in other words the first five characters.
Just like arrays, you can access the individual elements in a string using an
in-
dexer
. However, you cannot
change
this element since the
string
type is immutable.
The individual elements of a string are of the primitive
char
type, so you can store
them directly in a variable:
char
first;
first = s[0];
12.10
foreach
: Do Something with All the Items in a List or an
Array
Traversing a list to perform some operation on each item in the list is so common,
that for that purpose, a special iteration instruction is available called
foreach
.For
example, the following
foreach
-instruction draws all the snowflakes in the list on the
screen:
foreach
(Snowflake s
in
snowflakes)
s.Draw(gameTime, spriteBatch);
The
foreach
-instruction does away with the counter variable altogether. In each it-
eration, a local variable
s
represents the item that we are currently working on. Al-
though this is a very compact notation for iterating through a list, it is less powerful
than the full-fledged
for
-instruction, since we do not have control over which items
in the list are processed and in which order. The
foreach
-instruction can be used on
both arrays and lists. Here is the syntax diagram for the
foreach
-instruction: