Information Technology Reference
In-Depth Information
var rightOperand = Expression .Parameter( typeof (T),
"right" );
var body = Expression .Add(leftOperand, rightOperand);
var adder = Expression .Lambda< Func <T, T, T>>(
body, leftOperand, rightOperand);
compiledExpression = adder.Compile();
}
}
Yo u s t i l l n e e d t o s p e c i f y t h e o n e t y p e p a r a m e t e r w h e n y o u c a l l A d d . D o i n g
so does give you the advantage of being able to leverage the compiler to
create any conversions at the callsite. The compiler can promote ints to
doubles and so on.
There are also performance costs with using dynamic and with building
expressions at runtime. Just like any dynamic type system, your program
has more work to do at runtime because the compiler did not perform
any of its usual type checking. The compiler must generate instructions to
perform all those checks at runtime. I don't want to overstate this, because
the C# compiler does produce efficient code for doing the runtime check-
ing. In most cases, using dynamic will be faster than writing your own
code to use reflection and produce your own version of late binding. How-
ever, the amount of runtime work is nonzero; the time it takes is also
nonzero. If you can solve a problem using static typing, it will undoubtedly
be more efficient than using dynamic types.
When you control all the types involved, and you can create an interface
instead of using dynamic programming, that's the better solution. You can
define the interface, program against the interface, and implement the
interface in all your types that should exhibit the behavior defined by the
interface. The C# type system will make it harder to introduce type errors
in your code, and the compiler will produce more efficient code because
it can assume that certain classes of errors are not possible.
In many cases, you can create the generic API using lambdas and force
callers to define the code you would execute in the dynamic algorithm.
The next choice would be using expressions. That's the right choice if you
have a relatively small number of permutations for different types, and a
small number of possible conversions. You can control what expressions
get created and therefore how much work happens at runtime.
 
Search WWH ::




Custom Search