Comparison of .NET 2.0 and .NET 3.5
Last Saturday I presented on LINQ at Developer Developer Developer. I stated that that much of LINQ was syntactic sugar ( very good low fat sugar) and in fact much of the work being done by the compiler effectively did repetetive work that we do day to day.
I see this as very solid reoccurring theme in Microsoft development tools, if the developer is doing the same thing again and again, visual studio will aim to help without being too prescriptive.
During the talk I confidently stated that the compiler really was generating much the same or possibly identical code, I suggested that the attendees could look at home but somehow I ended up offering to do the job so here are some rough notes.
taking the two snippets of code
for .Net 2.0
List
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
List
foreach (int evenNumber in evenNumbers)
{
Console.WriteLine(evenNumber);
}
and its LINQ equivalent
var list = new List
var evenNumbers = list.FindAll(i=>(i % 2) == 0);
foreach (var evenNumber in evenNumbers)
{
Console.WriteLine(evenNumber);
}
looking at the IL code that is generated for the anonymous delegate / lamda function we see that the code is identical for both
.method private hidebysig static bool
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor()
.maxstack 2
.locals init (
[0] bool flag1)
L_0000: nop
L_0001: ldarg.0
L_0002: ldc.i4.2
L_0003: rem
L_0004: ldc.i4.0
L_0005: ceq
L_0007: stloc.0
L_0008: br.s L_000a
L_000a: ldloc.0
L_000b: ret
}
which is the equivalent to
[CompilerGenerated]
private static bool
{
return ((i % 2) == 0);
}
Obviously the method name changes but that is the only change.
For the main block of code the only difference is the LINQ code generates a temporary List, populates it and then assigns it to the variable list. I can only assume that this is the implementation method of assignment, but I would hope it will come out in the wash, not that in the grand scheme it matters, but it would be a bit tidier.
I will be looking at other examples and posting my findings over the next week or so.
Boss.