CHAPTER 12 LINQ TO OBJECTS
}
Console.WriteLine();
Lambdas will be very useful when working with the underlying object model of LINQ. As you will
soon find out, the C# LINQ query operators are simply a shorthand notation for calling true-blue
methods on a class named System.Linq.Enumerable. These methods typically always require delegates
(the Func<> delegate in particular) as parameters, which are used to process your data to yield the correct
result set. Using lambdas, you can streamline your code, and allow the compiler to infer the underlying
delegate.
Extension Methods
C# extension methods allow you to tack on new functionality to existing classes without the need to
subclass. As well, extension methods allow you to add new functionality to sealed classes and structures,
which could never be subclassed in the first place. Recall from Chapter 11, when you author an
extension method, the first parameter is qualified with the this keyword, and marks the type being
extended. Also recall that extension methods must always be defined within a static class and must,
therefore, also be declared using the static keyword. For example:
namespace MyExtensions
{
static class ObjectExtensions
{
// Define an extension method to System.Object.
public static void DisplayDefiningAssembly(this object obj)
{
Console.WriteLine("{0} lives here:\n\t->{1}\n", obj.GetType().Name,
Assembly.GetAssembly(obj.GetType()));
}
}
}
To use this extension, an application must import the namespace defining the extension (and
possibly set a reference to the external assembly). At this point, simply import the defining namespace,
and code away:
static void Main(string[] args)
{
// Since everything extends System.Object, all classes and structures
// can use this extension.
int myInt = 12345678;
myInt.DisplayDefiningAssembly();
}
System.Data.DataSet d = new System.Data.DataSet();
d.DisplayDefiningAssembly();
Console.ReadLine();
When you are working with LINQ, you will seldom, if ever, be required to manually build your own
extension methods. However, as you create LINQ query expressions, you will actually be making use of
numerous extension methods already defined by Microsoft. In fact, each C# LINQ query operator is a
shorthand notation for making a manual call on an underlying extension method, typically defined by
the System.Linq.Enumerable utility class.
442