Fundamentals of Computer Programming with C# HTML version

Chapter 22. Lambda
Expressions and LINQ
In This Chapter
In this chapter we will become acquainted with some of the advanced
capabilities of the C# language. To be more specific, we will pay attention on
how to make queries to collections, using lambda expressions and LINQ,
and how to add functionality to already created classes, using extension
methods. We will get to know the anonymous types, describe their usage
briefly and discuss lambda expressions and show in practice how most of the
built-in lambda functions work. Afterwards, we will pay more attention to
the LINQ syntax – we will learn what it is, how it works and what queries we
can build with it. In the end, we will get to know the meaning of the
keywords in LINQ, and demonstrate their capabilities with lots of examples.
Extension Methods
In practice, programmers often have to add new functionality to already
existing code. If the code is available, we can simply add the required
functionality and recompile. When a given assembly (.exe or .dll file) has
already been compiled, and the source code is not available, a common way
to extend the functionality of the types is trough inheritance. This approach
can be quite difficult to apply, due to the fact that we will have to change the
instances of the base class with the instances of the derived one to be able to
use our new functionality. Unfortunately, that is the least of our problems. If
the type we want to inherit is marked with the keyword sealed, inheritance is
not possible.
Extension methods solve that very same problem – they present to us the
opportunity to add new functionality to already existing type (class or
interface), without having to change its original code or use inheritance, i.e.
also works fine with types that cannot be inherited. Notice that trough
extension methods we can add “implemented methods” even to interfaces.
The extension methods are defined as static in ordinary static classes.
The type of their first argument is the class (or the interface) they extend. In
front of it, we should place the keyword this. That is what makes them
different from other static methods, and indicates the compiler that this is an
extension method. The parameter with the keyword this in front of it can be
used in the method body to create its functionality. Practically, it is the object
that is used by the extension method.