Information Technology Reference
In-Depth Information
Dynamic is not free. There's quite a bit of code generated by the compiler
to make dynamic invocation work in C#. Worse, this code will be repeated
everywhere that you invoke the dynamic Add() method. That's going to
have size and performance implications on your application. You can wrap
the Add() method shown in Item 38 in a bit of generic syntax to create a
version that keeps the dynamic types in a constrained location. The same
code will be generated but in fewer places:
private static dynamic DynamicAdd(dynamic left,
dynamic right)
{
return left + right;
}
// Wrap it:
public static T1 Add<T1, T2>(T1 left, T2 right)
{
dynamic result = DynamicAdd(left, right);
return (T1)result;
}
The compiler generates all the dynamic callsite code in the generic Add()
method. That isolates it into one location. Furthermore, the callsites
become quite a bit simpler. Where previously every result was dynamic,
now the result is statically typed to match the type of the first argument.
Of course, you can create an overload to control the result type:
public static TResult Add<T1, T2, TResult>
(T1 left, T2 right)
{
dynamic result = DynamicAdd(left, right);
return (TResult)result;
}
In either case, the callsites live completely in the strongly typed world:
int answer = Add( 5 , 5 );
Console .WriteLine(answer);
double answer2 = Add( 5.5 , 7.3 );
Console .WriteLine(answer2);
 
Search WWH ::




Custom Search