ChrisRohlf
ChrisRohlf

Reputation: 51

Using the Mono C# compiler as a service (error)

I'm relatively new to Mono and I am trying to add C# scripting capabilities to my application. I found this blog post by Miguel de Icaza. The way to call the C# compiler as a service is to include Mono.CSharp and use the Evaluator class, specifically the Evaluate or Run methods. This is documented here.

So here is my example code (derived from the other blog posts on the internet on this subject, yes I've done my googling)

using System;
using Mono.CSharp;

namespace EvalTest
{
  public class Test
  {
    static void Main(string [] args)
    {
      Mono.CSharp.Evaluator.Evaluate("using System;");
      Mono.CSharp.Evaluator.Run("using System;");
    }
  }
}

And when we try to compile it I get these errors:

eval.cs(10,19): error CS0234: The type or namespace name `Evaluator' does not exist in the namespace `Mono.CSharp'. Are you missing an assembly reference?
eval.cs(11,19): error CS0234: The type or namespace name `Evaluator' does not exist in the namespace `Mono.CSharp'. Are you missing an assembly reference?

The same thing happens on Linux and OSX using all the Mono compilers, I even tried the silverlight one. I have searched stackoverflow for similar questions, everyone references Miguel's blog post and some similar sample code. What am I missing? Is there some compiler flag I need to add? Thanks for your help.

Upvotes: 3

Views: 1604

Answers (2)

Hans Passant
Hans Passant

Reputation: 941635

Are you missing an assembly reference?

It's one of those psychic error messages that tends to be right 95% of the time. Go back to the blog post and note this line:

Usage is very simple, you must reference the `gmcs.exe' assembly

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500903

Did you follow this bit of the blog post:

Usage is very simple, you must reference the `gmcs.exe' assembly

? This is what I did with your code (in Test.cs):

c:\Users\Jon\Test>copy "c:\Program Files (x86)\Mono-2.8"\lib\mono\2.0\gmcs.exe .
        1 file(s) copied.

c:\Users\Jon\Test>gmcs /r:gmcs.exe Test.cs

c:\Users\Jon\Test>mono Test.exe

Unhandled Exception: System.ArgumentException:
  The expression did not set a result
  at Mono.CSharp.Evaluator.Evaluate (System.String input) [...]
  at EvalTest.Test.Main (System.String[] args) [...]

It's fair enough that it doesn't give any result - it's only a using directive. This works fine though:

Mono.CSharp.Evaluator.Run("System.Console.WriteLine(5 + 5);");

Upvotes: 6

Related Questions