Thursday 11 September 2008

LINQ Source Code (or LINQ for .NET 2.0)

Background

Recently, I had to make some enhancements in a large stabilised asp.net solution. As usual, I began testing some code in a new project as a small proof of concept. After I was done, I realized that the old code was made using VS 2005 (i.e., over .NET Framework 2.0) and my test code used a lot of LINQ (i.e., over .NET Framework 3.5). Since upgrading the solution was not allowed, my only option was to remove Linq from my code. Or maybe not.

Using VS 2008, it's possible to use almost all the features of C# 3.0 even in a project targetting the 2.0 framework. The exception is Linq, because it inherently references extension functions that are only present in the 3.5 framework. Since I needed only Where() and Select(), I simply coded them and it worked just fine. I saw it was possible to write code for all the Linq to Objects extension methods. Better yet, I could aquire it from a more trustful source.

Linq to Objects Source Code

It's publicly known that a good part of the .NET Framework source code is available for anyone to download. Unfortunately, the code for Linq to Objects was not released yet. The alternative was to disassemble the assembly using .NET Reflector (I hope MS will not sue me for this). Anyway, as the code was not genuinely authored by me, I took special care of not using my namespace (JpLabs) in it.

One thing that Reflector don't do is to simplify functions that use yield return. Instead, it shows what is actually compiled, i.e., one compiler-generated iterator class for each function. These classes use state machines to control the iteretion. If you want to see how such a class looks like, try using Reflector. If you're not familiarised to yield return, you might want to check this arcticle. I decompiled all the iterator functions in Linq to Objects manually.

To make this post short, I would like to say that, in addition to the existent Linq extension functions, I've included some of my own, like ForEach(Action action).

Download

Download the full source here.

[Update @2008.09.25]
I've just found out that there is a project with the exactly the same purpose as the one in this post. And the authors are much more reliable than me. Check out the LINQBridge from the Albahari brothers. As mine, their code is completely open and free for any use.

Also, I would like to suggest the excellent free book on Threading in C# on their web page. It's definitely the most complete and most readable source on this subject that I know of.