k25 k25 - 4 months ago 29
C# Question

Roslyn: Effect of CSharpCompilerOptions WithUsings

My question is about

CSharpCompilerOptions
and
using
statements passed to an instance of
CSharpCompilation
.

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();
Console.WriteLine(message);
}
}
}");


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(
assemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
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!

Answer

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).