Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does LINQPad compile code?

Tags:

c#

linqpad

I am guessing it neither invokes csc.exe or implement an entire compiler, so how does it work?

Update: Thanks to Jon Skeet for the pointer to code that was easy to learn from.

string c = @"
public class A
{
    public static void Main(string[] args)
    {
        System.Console.WriteLine(""hello world"");
    }
}
";

CodeDomProvider compiler = new CSharpCodeProvider();

CompilerParameters parameters = new CompilerParameters();
parameters.WarningLevel = 4;
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;

CompilerResults r = compiler.CompileAssemblyFromSource(parameters, c);

Assembly a = r.CompiledAssembly;

Type[] ts = a.GetTypes();

Type t = ts[0];

object o = t.GetMethod("Main").Invoke(null, new object[] { new string[] { } });
like image 683
Aaron Anodide Avatar asked Apr 23 '11 19:04

Aaron Anodide


People also ask

How does LINQPad work?

LINQPad automatically patches itself by downloading updates into its Application Data folder. It then checks that the new assembly has a valid signature, and if so, forwards to that executable, which then writes itself back to the original file.

Why is LINQPad used?

LINQPad is a software utility targeted at . NET Framework and . NET Core development. It is used to interactively query SQL databases (among other data sources such as OData or WCF Data Services) using LINQ, as well as interactively writing C# code without the need for an IDE.

How do I run a query in LINQPad?

Click on "Add connection"; a window will appear. Choose "Default (LINQ to SQL)" and click on the "Next" button. A new window will appear, fill in the required details to get connected with the desired database.

What is. LINQ file?

A LINQ file is a text file created by LINQPad, a utility that helps . NET Framework developers test code outside of IDEs like Microsoft Visual Studio.


2 Answers

From "How LINQPad Works":

LINQPad compiles your queries using .NET's CSharpCodeProvider (or VBCodeProvider)

Obviously there's rather more to it, but that's the bit you asked about - read the link for more details.

If you want to have a look at a rather more simplistic implementation, you could download the source code for Snippy, the little tool I created for C# in Depth. Again, it uses CSharpCodeProvider - and it's a simple enough example that it's easy to understand, with any luck. (There are only a few classes involved, IIRC.)

like image 67
Jon Skeet Avatar answered Oct 02 '22 10:10

Jon Skeet


Jon's answer from almost 5 years ago is now out of date.

From "How LINQPad Works" (as at 29 Jan 2016):

LINQPad 5 compiles your queries using the Microsoft Roslyn libraries (in the past it used .NET's CSharpCodeProvider and VBCodeProvider).

You can see an example of how to use Roslyn to compile your code here: Learn Roslyn Now - Part 16 - The Emit API

like image 35
Edward Avatar answered Oct 02 '22 11:10

Edward