Information Technology Reference
In-Depth Information
proper type. You could do that, but it's a waste. Instead, C# 4.0 dynamic
can do all the heavy lifting. You're left with a simple Convert<T> that does
what you expect:
public static IEnumerable <TResult> Convert<TResult>(
this System.Collections. IEnumerable sequence)
{
foreach ( object item in sequence)
{
dynamic coercion = ( dynamic )item;
yield return (TResult)coercion;
}
}
Now, as long as there is a conversion (either implicit or explicit) from the
source type to the target type, the conversion works. There are still casts
involved, so the possibility for runtime failure exists. That's just part of
the game when you are coercing the type system. Convert<T> does work
in more situations than Cast<T>(), but it also does more work. As devel-
opers, we should be more concerned about what code our users need to
create than we are about our own code. Convert<T> passes this test:
var convertedSequence = GetSomeStrings().Convert<MyType>();
Cast<T>, like all generic methods, compiles with only limited knowledge
of its type parameters. That can lead to generic methods not working the
way you'd expect. The root cause is almost always that the generic method
could not be made aware of particular functionality in the type repre-
senting the type parameters. When that happens, a little application of
dynamic can enable runtime reflection to make matters right.
Item 40: Use Dynamic for Parameters That Receive
Anonymous Types
One of the shortcomings of anonymous types has been that you cannot
easily write methods using them as parameters or return types. Because the
compiler generated the anonymous type, you could not use them as
parameters to methods, or as return values from methods. Any solution to
the problem was necessarily limiting. You could use anonymous types as
generic type parameters, or you could use them with any method that used
System.Object as a parameter. None of those felt particularly satisfying.
 
 
Search WWH ::




Custom Search