Information Technology Reference
In-Depth Information
var answer3 = from v in GetSomeStrings()
select ( MyType )v;
foreach ( var v in answer3)
Console .WriteLine(v);
What's the difference? The two versions that don't work use Cast<T>(),
and the version that works includes the cast in the lambda used as the
argument to Select(). Cast<T> cannot access any user-defined conversions
on the runtime type of its argument. The only conversions it can make are
reference conversions and boxing conversions. A reference conversion suc-
ceeds when the is operator succeeds (see Item 3). A boxing conversion
converts a value type to a reference type and vice versa (see Item 45).
Cast<T> cannot access any user-defined conversions because it can only
assume that T contains the members defined in System.Object.
System.Object does not contain any user-defined conversions, so those are
not eligible. The version using Select<T> succeeds because the lambda
used by Select() takes an input parameter of string . That means the con-
version operation defined on MyType.
As I've pointed out before, I usually view conversion operators as a code
smell. On occasion, they are useful, but often they'll cause more problems
than they are worth. Here, without the conversion operators, no developer
would be tempted to write the example code that didn't work.
Of course, if I'm recommending not using conversion operators, I should
offer an alternative. MyType already contains a read/write property to store
the string property, so you can just remove the conversion operators and
write either of these constructs:
var answer4 = GetSomeStrings().
Select(n => new MyType { StringMember = n });
var answer5 = from v in GetSomeStrings()
select new MyType { StringMember = v };
Also, if you needed to, you could create a different constructor for MyType.
Of course, that is just working around a limitation in Cast<T>(). Now that
you understand why those limitations exist, it's time to write a different
method that gets around those limitations. The trick is to write the generic
method in such a way that it leverages runtime information to perform
any conversions.
Yo u c o u l d w r i t e p a g e s a n d p a g e s o f r e fl e c t i o n - b a s e d c o d e t o s e e w h a t c o n -
versions are available, perform any of those conversions, and return the
 
Search WWH ::




Custom Search