Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roslyn: Effect of CSharpCompilerOptions WithUsings

Tags:

c#

.net

roslyn

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!

like image 827
k25 Avatar asked Dec 05 '25 06:12

k25


1 Answers

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

like image 72
SLaks Avatar answered Dec 07 '25 20:12

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!