Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roslyn - CSharpCompilation

Tags:

c#

roslyn

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

My understanding is that the syntax tree will be compiled using the context of any using statements I pass through. However when trying to access a class which is defined in one of the 'usings' I pass to the options object I get an error saying it doesn't exist in the current context.

I am clearly doing something wrong. Anybody know what the list of usings is for when passed 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)
            {
            }
        }
    }
like image 882
user2697817 Avatar asked Jul 09 '14 15:07

user2697817


1 Answers

So, it turns out that CSharpCompilationOptions.Usings is only ever examined in the compiler when compiling script files. If you trace through the references, it ends up getting used here, inside an if (inScript) check.

We probably need to document that better.

like image 64
Kevin Pilch Avatar answered Sep 28 '22 07:09

Kevin Pilch