Search code examples
c#.netroslynconditional-compilation

Perform Roslyn conditional compilation with custom symbol (eg: "DEBUG") defined


I'm compiling a project using Roslyn with code resembling:

var workspace = MSBuildWorkspace.Create();
var project = await workspace.OpenProjectAsync("SomeProject.csproj");
var compilation = await project.GetCompilationAsync();

I need to set a compilation symbol (such as DEBUG or TRACE, but in my case something altogether custom). How can I do this with the API?

I saw that project has a CompilationOptions property, but I didn't see anything relevant there.


EDIT Thanks to @JoshVarty who pointed towards adding code like this prior to compilation:

project = project
    .WithParseOptions(((CSharpParseOptions)project.ParseOptions)
    .WithPreprocessorSymbols("SOME_SYMBOL"));

Solution

  • I think you're looking for Project.WithParseOptions() and WithPreprocessorSymbols()