Information Technology Reference
In-Depth Information
var small = from int item in collection
where item < 5
select item;
var small2 = collection.Cast< int >().Where(item => item < 5 ).
Select(n => n);
The query generates the same method calls as the last line of code above.
In both cases, the Cast<T> method converts each item in the sequence to
the target type. The Enumerable.Cast<T> method uses an old style cast
rather than the as operator. Using the old style cast means that Cast<T>
does not need to have a class constraint. Using the as operator would be
limiting, and rather than implement different Cast<T> methods, the BCL
team chose to create a single method using the old style cast operator. It's
a tradeoff you should consider in your code as well. On those occasions
where you need to convert an object that is one of the generic type param-
eters, you'll need to weigh the necessity of a class constraint against the
different behavior of using the cast operator.
In C# 4.0, the type system can be circumvented even more by using
dynamic and runtime type checking. That's the subject of Chapter 5,
“Dynamic Programming in C#.” There are quite a few ways to treat objects
based on expectations of known behavior rather than knowing anything
about a particular type or interface supplied. You'll learn about when to
use those techniques and when to avoid them.
Good object-oriented practice says that you should avoid converting types,
but sometimes there are no alternatives. If you can't avoid the conversions,
use the language's as and is operators to express your intent more clearly.
Different ways of coercing types have different rules. The is and as oper-
ators are almost always the correct semantics, and they succeed only when
the object being tested is the correct type. Prefer those statements to cast
operators, which can have unintended side effects and succeed or fail when
you least expect it.
Item 4: Use Conditional Attributes Instead of #if
#if/#endif blocks have been used to produce different builds from the
same source, most often debug and release variants. But these have never
been a tool we were happy to use. #if/#endif blocks are too easily abused,
creating code that is hard to understand and harder to debug. Language
 
 
Search WWH ::




Custom Search