Information Technology Reference
In-Depth Information
level. Other languages, in particular VB.NET, did define query syntax for
many of these keywords.
This is the part of any discussion where someone usually asserts that
queries perform more slowly than other loops. While you can certainly
create examples where a hand-coded loop will outperform a query, it's not
a general rule. You do need to measure performance to determine if you
have a specific case where the query constructs don't perform well enough.
However, before completely rewriting an algorithm, consider the parallel
extensions for LINQ. Another advantage to using query syntax is that you
can execute those queries in parallel using the .AsParallel() method. (See
Item 35.)
C# began as an imperative language. It continues to include all the fea-
tures that are part of that heritage. It's natural to reach for the most famil-
iar tools at your disposal. However, those tools might not be the best tools.
When you find yourself writing any form of a looping construct, ask your-
self if you can write that code as a query. If the query syntax does not work,
consider using the method call syntax instead. In almost all cases, you'll
find that you create cleaner code than you would using imperative loop-
ing constructs.
Item 9: Avoid Conversion Operators in Your APIs
Conversion operators introduce a kind of substitutability between classes.
Substitutability means that one class can be substituted for another. This
can be a benefit: An object of a derived class can be substituted for an
object of its base class, as in the classic example of the shape hierarchy. You
create a Shape base class and derive a variety of customizations: Rectangle,
Ellipse, Circle, and so on. You can substitute a Circle anywhere a Shape is
expected. That's using polymorphism for substitutability. It works because
a circle is a specific type of shape. When you create a class, certain conver-
sions are allowed automatically. Any object can be substituted for an
instance of System.Object, the root of the .NET class hierarchy. In the same
fashion, any object of a class that you create will be substituted implicitly
for an interface that it implements, any of its base interfaces, or any of its
base classes. The language also supports a variety of numeric conversions.
When you define a conversion operator for your type, you tell the compiler
that your type may be substituted for the target type. These substitutions
often result in subtle errors because your type probably isn't a perfect sub-
 
 
Search WWH ::




Custom Search