Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

mono

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.

like image 467
ChrisRohlf Avatar asked Dec 14 '25 10:12

ChrisRohlf


2 Answers

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);");
like image 63
Jon Skeet Avatar answered Dec 16 '25 23:12

Jon Skeet


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

like image 38
Hans Passant Avatar answered Dec 16 '25 23:12

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!