Compilation errors when working with C # script using Roslyn

I am implementing the C # script engine in my application using Roslyn, and so far I can execute the code without problems. I can, for example, execute the following code:

using System; var str = "Hello Roslyn"; Console.WriteLine(str); 

I have to face compilation problems when creating my syntax tree from the code snippet above. The compiler complains about statements directly embedded in the main namespace, which makes sense when writing a regular program in C #, but not in my case, when I switch to the script path.

Question: Is there a way to build a syntax tree without errors from a C # script?

EDIT Here is the code that I use to build the syntax tree.

 SyntaxTree tree = SyntaxTree.ParseText(context.SourceCode); Compilation compilation = Compilation.Create("CSharp", syntaxTrees: new[] {tree}, references: references); 

thanks

+4
source share
1 answer

You need to indicate that you are casting script code instead of regular code:

 SyntaxTree tree = SyntaxTree.ParseText(source, options: new ParseOptions(kind: SourceCodeKind.Script)); 
+7
source

All Articles