Game Development Reference
In-Depth Information
The code creates a list and adds two decimal numbers. Everything in C# is an
object, including numbers. All objects in C# inherit from the object class.
An ArrayList stores objects. Here, numbers have been added but the
ArrayList does not know they are numbers; to the ArrayList they are just
objects. Objects are the only thing it knows. When the number is passed to
ArrayList.Add it is converted to an object type and added to its collec-
tion of objects.
Every time an object is taken out of the list, it must be cast back from an object
to its original type. All the casts are inefficient and they clutter the code making
it harder to read, which makes non-generic code unpleasant to work with.
Generics fix this problem. To understand how they fix the problem, you need to
understand the difference between reference types and value types.
C# has two broad categories of type, reference types and value types. Value types
are the basic types such as int , float , double , bool , string , etc. Reference
types are the large data structures you define yourself using the class keyword
such as Player , Creature , Spaceship , etc. You can also define custom
value types using the struct keyword.
// An example reference type
public class SpaceShip
{
string _name;
int _thrust;
}
// An example value type
public struct Point
{
int _x;
int _y;
}
Value types store their data directly in memory. Reference types store their data
indirectly in memory. In the memory address of a reference type is another
memory address to where the data is actually stored. This can be confusing at
first, but once you are familiar with the concepts it's quite simple. The differ-
ences in memory are shown in Figure 1.2.
If the computer's memory is thought of as a vast library full of bookshelves, then
creating a value type is simply adding some topics to the shelf. Creating a
 
Search WWH ::




Custom Search