Information Technology Reference
In-Depth Information
When you use dynamic, the underlying dynamic infrastructure will work
to make any possible legal construct work, no matter how expensive the
work is at runtime.
However, for the Add() method I demonstrated at the beginning of this
item, that's not possible. Add() should work on a number of types that are
already defined in the .NET class library. You can't go back and add an
IAdd interface to those types. You also can't guarantee that all third-party
libraries you want to work with will conform to some new interface. The
best way to build methods based on the presence of a particular member
is to write a dynamic method that defers that choice to the runtime. The
dynamic implementation will find a proper implementation, use it, and
cache for better performance. It's more expensive than a purely statically
typed solution, and it's much simpler than parsing expression trees.
Item 39: Use Dynamic to Leverage the Runtime Type of Generic
Ty p e P a r a m e t e r s
System.Linq.Enumerable.Cast<T> coerces every object in a sequence to
the target type of T. It's part of the framework so that LINQ queries can
be used with sequences of IEnumerable (as opposed to IEnumerable<T>).
Cast<T> is a generic method, with no constraints on T. That limits the
types of conversions available to it. If you use Cast<T> without under-
standing its limitations, you'll find yourself thinking it doesn't work. In
reality, it's working exactly as it should, just not the way you expect. Let's
examine its inner workings and limitations. Then, it will be easy to create
a different version that does what you expect.
The root of the problem lies with the fact that Cast<T> is compiled into
MSIL without any knowledge of T beyond the fact that T must be a man-
aged type that derives from System.Object. Therefore, it does its work only
using the functionality defined in System.Object. Examine this class:
public class MyType
{
public String StringMember { get ; set ; }
public static implicit operator String ( MyType aString)
{
return aString.StringMember;
}
 
 
Search WWH ::




Custom Search