David Klempfner
David Klempfner

Reputation: 9870

C# Compiled to CIL

I understand that the following C# code:

var evens = from n in nums where n % 2  == 0 select n;

compiles to:

var evens = nums.Where(n => n % 2 == 0);

But what does it mean that it compiles to that? I was under the impression that C# code compiles directly into CIL?

Upvotes: 6

Views: 669

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 148980

I think you've misunderstood something. The query expression:

var evens = from n in nums where n % 2 == 0 select n;

doesn't compile to:

var evens = nums.Where(n => n % 2 == 0);

Rather, the two lines of code compile directly to CIL. It just so happens that they compile to (effectively) identical CIL. The compiler may convert the query to an intermediate form in the process of analyzing the query code, but the ultimate result is, of course, CIL.

Upvotes: 2

paulsm4
paulsm4

Reputation: 121599

This is a C#/LINQ expression:

var evens = from n in nums where n % 2 == 0 select n;

This is a C# lambda expression:

var evens = nums.Where(n => % 2 == 0);

They are both C#, and they both get compiled into CIL.

You can read more about lambdas here:

You can read more about LINQ here:

The two expressions are equivalent.

One does NOT get "compiled" into the other. Honest :)

Upvotes: 1

Related Questions