C# Compiler as a Service Update

by Miguel de Icaza

Our C# compiler-as-a-service library can now process any C# construct, it is no longer limited to expressions and statements.

This means, that you can now enter entire class definitions in the command line:

csharp> class Demo {
      >     public int Add (int a, int b)
      >     {
      >          return a + b;
      >     }
      > }
csharp> new Demo ().Add (1, 3);

This work was done by the amazing Marek and is now available on Mono's master branch in github.

This functionality can also be used for scripts, in particular in Unix, you can now create C# "source executable" files, like this:

bash$ cat demo.cs
class Demo {
	public dynamic Add (dynamic a, dynamic b)
		return a + b;
Console.WriteLine (new Demo ().Add ("this is", " cute"));
bash$ chmod +x demo.cs
bash$ ./demo.cs
this is cute

Multiple Compiler Instances

In addition, we turned the static API Evalutor.Eval (string expression), into an instance API. The instance API allows developers that are embedding the C# compiler-as-a-service in their application to have different contexts.

This required the entire compiler to be updated from being a giant set of static classes that could safely use global variables and state into a state that was properly encapsulated.

The API is now richer, we provide a way to configure the compiler settings using a settings class. This can be populated either manually, or by using the build-in command-line parser for compiler options. The following sample shows how this could be used:

using Mono.CSharp;
using System;

class Runner {
	static int Main (string [] args)
		var r = new Report (new ConsoleReportPrinter ());
		var cmd = new CommandLineParser (r);
		var settings = cmd.ParseArguments (args);
		if (settings == null || r.Errors > 0)
			Environment.Exit (1);

		var evaluator = new Evaluator (settings, r);

		evaluator.Run ("class Demo { public static int Add (int a, int b) { return a+b; }}");
		evaluator.Run ("print (Demo.Add (1,2));");
		return 0;

Testers Wanted

This revamped compiler will be part of Mono 2.12, but we would love to get users to test the new functionality and to help us identify any problems early on, before we even release this code.

We do provide a convenient sln file that you can use the compiler as a service, and it works both in Visual Studio/.NET and Mono.


We have not tested this with Silverlight, but in theory, it should now work fine with it. We would love to see someone build an interactive shell like the one we did with Gtk# but hosted on the browser:

Posted on 24 Feb 2011