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!
/// Global namespace usings.in source.roslyn.io/#Microsoft.CodeAnalysis.CSharp/… line 27. Those namespaces can be accessed under theglobal::namespace alias msdn.microsoft.com/en-us/library/c3ay4x3d.aspx if I'm right, switch it toglobal::WebClient client = new global::WebClient();and it will work withusing System.Net;commented out.