Game Development Reference
In-Depth Information
dynamic testObj ¼ GetDynamicObject();
testObj.ICanCallAnyFunctionILike();
The method ICanCallAnyFunctionILike probably doesn't exist, so when
the program runs and executes that section of code, it will throw an exception.
Calling any method or accessing any member of a dynamic object requires the
object to do a runtime look-up to see if that member or method exists. That
means if the programmer makes a typo, the error isn't caught during compiling,
only when the code is run. In C# if a method or field on a dynamic object isn't
found, the exception that's thrown is of type RuntimeBinderException .
The dynamic keyword is useful if you intend to do a lot of dynamic scripting in
your game or if you want write a function that takes advantage of duck typing, as
in the PrintName example. PrintName is slower because the GetNames
method must be looked up each time it is called. It may be worth taking the
speed hit in certain situations, but it's best to be aware of it.
Optional Parameters and Named Arguments
Until version 4.0, C# had no support for optional parameters in methods. This is
a standard feature of C
þþ
. Here's how it works.
class Player
{
// Knock the player backwards
public void KnockBack(int knockBackDamage ¼ 0)
{
// code
}
}
Player p ¼ new Player();
p.KnockBack(); // knocks the player back and by default deals no damage
p.KnockBack(10); // knocks the player back and gives 10 damage
Optional parameters allow the programmer to give default values to the method
arguments. Named arguments allow multiple optional parameters to be used in
an elegant way.
enum HairColor
{
Blonde,
Brunette,
 
Search WWH ::




Custom Search