Game Development Reference
In-Depth Information
processed by removing them one by one from the front of the queue and han-
dling them in order. A variation of this kind of data structure is the Stack class,
which allows you to push elements onto the stack, and pop elements from the top
again.
12.9 The Array: A Simpler Version of the List
Next to the collection classes, C# also has a more basic data structure called an
array . An array basically is a simplified version of a List object. For example, we
can declare an array of integers as follows:
int [] table;
The brackets indicate in this case that we are not declaring a single integer variable,
but an array of int variables. Declaring the array is not enough to be able to use it.
We have to initialize it beforehand:
table = new int [5];
We can assign values to the items in the array as follows:
table[3] = 4;
table[0] = 1;
As you can see, arrays also start from index 0. The elements in an array can also be
used in an expression, such as:
int x = table[3] + 12;
Furthermore, arrays have a property called Length which allows us to determine the
size of the array:
if (table.Length > 10)
dosomething...
When looking at the array declaration, we immediately see the disadvantage of us-
inganarrayovera List : when we initialize an array, we need to specify its size,
and this size cannot be changed afterwards. So if we initialize our table array with
size 5, but later on in the game we realize that we need a larger size, then there is
only one way to do it: copy the entire array into a temporary array, create a new
(larger) array, and copy all the elements back. A List on the other hand, has a dy-
namic size: we can add elements to it or remove elements from it once it has been
initialized.
So why should we use arrays at all? One of the times when arrays are very useful
is when we need a multidimensional structure such as a grid. For example, we can
declare a two-dimensional array as follows:
Search WWH ::




Custom Search