GETah
GETah

Reputation: 21449

Compilation errors when dealing with C# script using Roslyn

I am embedding a C# script engine into my application using Roslyn and so far, I can execute code with no issues. I can for example execute the following code:

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

I am facing compilation issues when building my syntax tree out the code snippet above. The compiler complains about statements directly embedded into the main namespace which makes sense when writing a normal C# program but not in my case as I am going the script way.

Question: Is there a way to build an error free syntax tree out of a C# script?

EDIT Here is the code I am using to build the syntax tree.

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

Thank you

Upvotes: 4

Views: 1433

Answers (1)

Jason Malinowski
Jason Malinowski

Reputation: 19031

You need to specify that you're parsing script code instead of regular code:

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

Upvotes: 8

Related Questions