Roslyn - CSharpCompilation

I use the CSharpCompilation class to compile SyntaxTree , where the root is the class declaration. I pass the constructor a CSharpCompilationOptions object that contains my using statements.

My understanding is that the syntax tree will be compiled using the context of any use of the statements that I pass. However, when I try to access the class that is defined in one of the "applications", I go to the options object, I get an error message that does not exist in the current context.

I am clearly doing something wrong. Does anyone know what a message list is for when it moved to the CSharpCompilationOptions class?

This is the code:

 public static void TestMethod() { string source = @"public class Test { public static void TestMethod() { string str = Directory.GetCurrentDirectory(); } }"; SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source); List<string> usings = new List<string>() { "System.IO", "System" }; List<MetadataFileReference> references = new List<MetadataFileReference>() { new MetadataFileReference(typeof(object).Assembly.Location), }; //adding the usings this way also produces the same error CompilationUnitSyntax root = (CompilationUnitSyntax)syntaxTree.GetRoot(); root = root.AddUsings(usings.Select(u => SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName(u))).ToArray()); syntaxTree = CSharpSyntaxTree.Create(root); CSharpCompilationOptions options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: usings); CSharpCompilation compilation = CSharpCompilation.Create("output", new[] { syntaxTree }, references, options); using (MemoryStream stream = new MemoryStream()) { EmitResult result = compilation.Emit(stream); if (result.Success) { } } } 
+8
c # roslyn
source share
1 answer

So it turns out that CSharpCompilationOptions.Usings is only checked in the compiler when compiling script files. If you trace the links, it eventually gets here , inside the if (inScript) .

We probably need to document which is better.

+5
source share

All Articles