Game Development Reference
In-Depth Information
List < float > _list ¼ new List < float > ();
_list.Add(1);
_list.Add(5.6f);
float valueOne ¼ _list[0];
float valueTwo ¼ _list[1];
This example code creates a list of floats . Floats are value types. Unlike before,
the floats don't have to boxed and unboxed by casting; instead it just works.
The generic list knows the type it is storing so it doesn't need to cast everything to
an object type. This makes the code far more efficient because it's not always
swapping between types.
Generics are great for building reusable data structures like lists.
Anonymous Delegates
In C# a delegate is a way of passing a function as an argument to another func-
tion. This is really useful when you want to do a repetitive action to many dif-
ferent lists. You have one function that iterates through the list, calling a second
function to operate on each list member. Here is an example.
void DoToList(List < Item > list, SomeDelegate action)
{
foreach(Item item in list)
{
action(item);
}
}
Anonymous delegates allow the function to be written straight into the DoToList
function call. The function doesn't need to be declared or predefined. Because it's
not predefined, it has no name, hence anonymous function.
// A quick way to destroy a list of items
DoToList(_itemList, delegate(Item item) { item.Destroy(); });
This example iterates through the list and applies the anonymous function to
each member. The anonymous function in the example calls the Destroy
method on each item. That could be pretty handy, right? But there's one more
trick to anonymous functions. Have a look at the following code.
int SumArrayOfValues(int[] array)
{
int sum ¼ 0;
 
Search WWH ::




Custom Search