Game Development Reference
In-Depth Information
Note
To use the
Dictionary
class, as well as the
List
class, we must include the
System.Collections.Generic
namespace (see line 03).
More information on the
Dictionary
class can be found online at
Information on the
List
class can be found at
The declaration itself occurs at
line 08
and makes use of
Generic
(or
Template
) classes
(further considered in the next section). In essence, this line creates a Dictionary of events and
listeners. The key values (
event types
) are specified as string elements—representing human-readable
names of events we'll use (such as
OnHealthChange
), and the listeners themselves are specified as a
list
of
components
, using the .NET
List
class. All components associated with an event will be notified
when the event happens through function calls.
Generic Classes and C#
In the previous section, we added a two-dimensional dynamic array member to the
NotificationsManager to act as an organized and searchable collection of
Event a
nd
Listener
objects. This was implemented on line 08 of Listing 3-7, using the
Dictionary
and
List
classes from
the .NET Framework. In declaring both these classes in just one line, we relied on the concept of
Generic
(or
Template
) classes. Let's discuss these further here for clarity.
If you go online and examine the Microsoft documentation for the
List
class at
http://msdn.microsoft.com/en-us/library/6sh2ey19%28v=vs.110%29.aspx
, you'll see from the title
section that List is written as
List<T>
. Notice the
<T>
post-fix in that title. What does that mean?
In short, the post-fix
<T>
, when applied to a class, means the class is
not
strictly typed, and instead
uses
Generics,
which are a loose, stand-in data type that mean whatever you want them to mean. It
means the
List
class is not restricted to being a list of
integers
, or a list of
strings
, or a list of
chars
,
or a list of
components
. It can be
any
of these if you want it to be, as well as any other data type you
may want it to be. Consequently, a list of integers can be made with
List<
int
> MyIntegers = new List<
int
>();
And a list of strings with
List<
string
> MyStrings = new List<
string
>();
And a list of components with
List<
Component
> MyStrings = new List<
Component
>();
This means that the first element in the list, at List[0], will be an integer for integer lists, a string for
string lists, and so on. This powerful data-type versatility that comes from using Generics is not just
restricted to the .NET
List
class or to the .NET Framework itself. It is a C# language feature. The
Dictionary
class also uses Generics. Let's look at line 08 from Listing 3-7 again.
private Dictionary<
string
, List<
Component
>> Listeners = new Dictionary<string, List<Component>>();