k25 k25 - 5 months ago 47
C# Question

Roslyn: Effect of CSharpCompilerOptions WithUsings

My question is about

statements passed to an instance of

I have a syntax tree parsed from some text:

SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
namespace RoslynCodeAnalysis
using System;
using System.Net; // Commenting this out causes errors

public class Writer
public void Write(string message)
WebClient client = new WebClient();

The CSharpCompilation instance is created as below. I did not include the references for simplicity but it does add a reference to System.Net and few other common assemblies.

CSharpCompilation compilation = CSharpCompilation.Create(
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(
usings: new List<string> { "System", "System.Net" }));

The issue is that, if I comment out using System.Net, I get errors saying that:

CS0246: The type or namespace name 'WebClient' could not be found (are
you missing a using directive or an assembly reference?)

What could cause this? The options passed to CSharpCompilation has the usings property set to System and System.Net. Is this the normal behavior or am I missing something? Even though the usings property is specified, source text still needs to have the using statement? I am pretty sure I am missing something!


This is used for scripting, not normal file compilations.

If you trace usages of that property through Roslyn source, you'll end up here, which is used in the interactive pipeline (that's what a Submission is).