Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Compiled to CIL

Tags:

c#

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?

like image 542
David Klempfner Avatar asked Aug 06 '13 03:08

David Klempfner


2 Answers

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.

like image 67
p.s.w.g Avatar answered Oct 02 '22 19:10

p.s.w.g


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:

  • http://msdn.microsoft.com/en-us/library/vstudio/bb397687.aspx

  • http://www.dotnetperls.com/where

You can read more about LINQ here:

  • http://msdn.microsoft.com/en-us/library/vstudio/bb397687.aspx

The two expressions are equivalent.

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

like image 30
paulsm4 Avatar answered Oct 02 '22 19:10

paulsm4