Game Development Reference
In-Depth Information
_items.Add(new Item(''pet_hamster''));
_items.Add(new Item(''skull_helm''));
}
}
Initializing lists in this way requires a certain amount of setup code that has to be
put inside the constructor or in a separate initialization method. But by using
collection initializers everything can be written in a much more concise way.
class Orc
{
List < Item > _items ¼ new List < Item >
{
new Item(''axe''),
new Item(''pet_hamster''),
new Item(''skull_helm'')
};
}
In this example case, we don't use the constructor at all anymore; it's done
automatically when an object is created.
Local Variable Type Inference and Anonymous Types
Using code with generics can get a little messy if there are several generic objects
being initialized at the same time. Type inference can make things a little nicer.
List < List < Orc >> _orcSquads ¼ new List < List < Orc >> ();
In this code, there's a lot of repeated typing, which means more pieces of the
code to edit when changes happen. Local variable type inference can be used to
help out in the following way.
var _orcSquads ¼ new List < List < Orc >> ();
The var keyword is used when you would like the compiler to work out the
correct type. This is useful in our example as it reduces the amount of code that
needs to be maintained. The var keyword is also used for anonymous types.
Anonymous types occur when a type is created without a predefined class or
struct. The syntax is similar to the collection initializer syntax.
var fullName ¼ new { FirstName ¼ ''John'', LastName ¼ ''Doe'' };
 
Search WWH ::




Custom Search