Game Development Reference
In-Depth Information
The fullName object can now be used like a reference type. It has two read-
only fields, FirstName and LastName . This is useful when you have a func-
tion and you really want to return two values. Both values can be combined in an
anonymous type and returned. The more common use for anonymous type is
when storing the data returned from LINQ queries.
C# 4.0
C# 4.0 is the very latest release of C# and the major change is the addition of
dynamic types. C# is a statically typed language. Static typing means that all the
types of the various objects are known at compile time. Classes are defined with
fields and methods; these fields and methods don't change during the course of
the program. In dynamic typing, objects and classes are more fluid—functions
and fields can be added and taken away. IronPython and IronRuby are both
dynamic languages that run on the CLR.
Dynamic Objects
Dynamic objects get a new keyword: dynamic . Here's an example of how it's
used. Imagine we had several unrelated classes that all implemented a method
called GetName .
void PrintName(dynamic obj)
{
System.Console.Writeline(obj.GetName());
}
PrintName(new User(''Bob'')) // Bob
PrintName(new Monster(''Axeface'')) // Axeface
If an object is dynamic when a function is called, that function is looked up at
runtime. This is called duck typing. The look-up is done using reflection, or if the
object implements the interface IDynamicObject , then it calls the method
GetMetaObject and the object is left to deal with it internally. Duck typing is a
little slower because it takes time to determine if the function is present or not. In
traditional C#, a function or field's presence is determined once at compile time.
The following code will compile under C# 4.0.
public dynamic GetDynamicObject()
{
return new object();
}
 
Search WWH ::




Custom Search