Information Technology Reference
In-Depth Information
known method is available. This can be especially limiting when you want
to create a general method that relies on some operator, like +. Dynamic
invocation can fix that. As long as a member is available at runtime, it can
be used. Here's a method that adds two dynamic objects, as long as there
is an available operator + at runtime:
public static dynamic Add( dynamic left,
dynamic right)
{
return left + right;
}
This is my first discussion of dynamic, so let's look into what it's doing.
Dynamic can be thought of as “System.Object with runtime binding.” At
compile time, dynamic variables have only those methods defined in Sys-
tem.Object. However, the compiler adds code so that every member access
is implemented as a dynamic call site. At runtime, code executes to exam-
ine the object and determine if the requested method is available. (See
Item 41 on implementing dynamic objects.) This is often referred to as
“duck typing”: If it walks like a duck and talks like a duck, it may as well
be a duck. You don't need to declare a particular interface, or provide any
compile-time type operations. As long as the members needed are avail-
able at runtime, it will work.
For this method above, the dynamic call site will determine if there is an
accessible + operator for the actual runtime types of the two objects listed.
All of these calls will provide a correct answer:
dynamic answer = Add( 5 , 5 );
answer = Add( 5.5 , 7.3 );
answer = Add( 5 , 12.3 );
Notice that the answer must be declared as a dynamic object. Because the
call is dynamic, the compiler can't know the type of the return value. That
must be resolved at runtime. The only way to resolve the type of the return
code at runtime is to make it a dynamic object. The static type of the
return value is dynamic. Its runtime type is resolved at runtime.
Of course, this dynamic Add method is not limited to numeric type. You
can add strings (because string does have an operator + defined):
dynamic label = Add( "Here is " , "a label" );
 
Search WWH ::




Custom Search