Home Ask Login Register

Developers Planet

Your answer is one click away!

Farhad Alizadeh Noori February 2016

Programmatically compiling source code using Roslyn

So I've been trying to compile a piece of code programmatically with Roslyn. For some reasons the references that I add just don't end up in the Compilation class. So when I look at the referenced assembly after I use 'AddReferences', the list is empty. Hence, when I try to emit, I get "Object" not defined in the diagnostics. Can anyone point me to the problem?

Microsoft.CodeAnalysis.SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
public static class Program
    public static void Main()
    string autoreferences = @"mscorlib.dll,System.Core.dll";
    List<string> usings = new List<string>();
    string netAssembliesDirectory = Path.GetDirectoryName(typeof(object).Assembly.Location);
    var refs = new List<string>();
    foreach (string reference in autoreferences.Split(','))
        refs.Add(netAssembliesDirectory + "\\" + reference);

    CSharpCompilation compilation = CSharpCompilation.Create("ConsoleTest")
            new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings("System"))
    compilation.AddReferences(refs.Where(r => r != "").Select(r => MetadataReference.CreateFromFile(r)));
    var er = compilation.Emit(@"C:\" + "ConsoleTest");


SLaks February 2016

Roslyn objects are immutable.

compilation.AddReferences() returns a new compilation instance with those references.
You're ignoring that new instance.

You need to call Emit() on the compilation instance that has your references.

Post Status

Asked in February 2016
Viewed 2,835 times
Voted 7
Answered 1 times


Leave an answer

Quote of the day: live life