Information Technology Reference
In-Depth Information
Yo u c a n a d d a t i m e s p a n t o a d a t e :
dynamic tomorrow = Add( DateTime .Now, TimeSpan .FromDays( 1 ));
As long as there is an accessible operator +, the dynamic version of Add
will work.
This opening explanation of dynamic might lead you to overuse dynamic
programming. I've only discussed the pros of dynamic programming. It's
time to consider the cons as well. You've left the safety of the type system
behind, and with that, you've limited how the compiler can help you. Any
mistakes in interpreting the type will only be discovered at runtime.
The result of any operation where one of the operands (including a pos-
sible this reference) is dynamic is itself dynamic. At some point, you'll
want to bring those dynamic objects back into the static type system used
by most of your C# code. That's going to require either a cast or a conver-
sion operation:
answer = Add( 5 , 12.3 );
int value = ( int )answer;
string stringLabel = System. Convert .ToString(answer);
The cast operation will work when the actual type of the dynamic object
is the target type, or can be cast to the target type. You'll need to know the
correct type of the result of any dynamic operation to give it a strong type.
Otherwise, the conversion will fail at runtime, throwing an exception.
Using dynamic typing is the right tool when you have to resolve methods
at runtime without knowledge of the types involved. When you do have
compile-time knowledge, you should use lambda expressions and func-
tional programming constructs to create the solution you need. You could
rewrite the Add method using lambdas like this:
public static TResult Add<T1, T2, TResult>(T1 left, T2 right,
Func <T1, T2, TResult> AddMethod)
{
return AddMethod(left, right);
}
Every caller would be required to supply the specific method. All the pre-
vious examples could be implemented using this strategy:
var lambdaAnswer = Add( 5 , 5 , (a, b) => a + b);
var lambdaAnswer2 = Add( 5.5 , 7.3 , (a, b) => a + b);
 
Search WWH ::




Custom Search