Is there a way to enable "Implicit Usings" feature when compiling code with .NET Compiler SDK?

Mark M 0 Reputation points
2023-03-31T18:01:08.8166667+00:00

The "ImplicitUsings" feature allows code to omit usings statements for standard namespaces. Is there a way to tell a C# compilation to enable the feature and include such namespaces?

using System.Diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

var sourceText = "class C{" +
    "public void M(){" +
    " Console.Write(123);" +
    "}}";
var syntaxTree = CSharpSyntaxTree.ParseText(sourceText);

var coreReferences =
    ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES"))
    .Split(Path.PathSeparator)
    .Select(p => MetadataReference.CreateFromFile(p));
var compilation = CSharpCompilation.Create("MyAnalysis")
    .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
    .AddReferences(coreReferences)
    .AddSyntaxTrees(syntaxTree);

var diagnostics = compilation.GetDiagnostics();
Debug.Assert(diagnostics.Length == 0);
// diagnostics = "error CS0103: The name 'Console' does not exist in the current context"

In the above example, diagnostics contains the error that Console does not exist. If I add "using System" in the sourceText above, the code compiles without the error. Is there a way to enable the Implicit Usings feature so that compilation resolves symbols from standard namespaces?

Developer technologies C#
{count} votes

3 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-04-11T17:54:41.2933333+00:00

    implicit using is not part of the compiler, but actually the build system. when enabled, a c# file with global using statements is added to the project based the selected sdk.

    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive

    1 person found this answer helpful.

  2. Anonymous
    2023-04-03T03:27:15.1133333+00:00

    Hi @Mark M , welcome to Microsoft Q&A. For implicit references, only the files that are integrated in them are referenced automatically.

    You could check out this document: Implicit using directives. For libraries that are not included, you can manually add them in csproj. This way you don't need to add it again when you use it.

    <ItemGroup>
      <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.5.0" />
      <Using Include="Microsoft.CodeAnalysis" />
      <Using Include="Microsoft.CodeAnalysis.CSharp" />
      <Using Include= "System.Diagnostics" />
    </ItemGroup>
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  3. Mark M 0 Reputation points
    2023-04-12T21:06:54.2166667+00:00

    Based on all comments and using the document Jiale referenced, a possible solution is to create a global usings file(s) corresponding to specific known SDK(s). For example, for Microsoft.NET.Sdk I created the following file (Microsoft.NET.Sdk.usings.cs):

    global using System;
    global using System.Collections.Generic;
    global using System.IO;
    global using System.Linq;
    global using System.Net.Http;
    global using System.Threading;
    global using System.Threading.Tasks;
    

    Then I can load it and parse as an additional syntax tree getting rid of the compilation error. There are warnings about unnecessary using directives. The complete code is this:

    using System.Diagnostics;
    using Microsoft.CodeAnalysis;
    using Microsoft.CodeAnalysis.CSharp;
    
    var sourceText = "class C{" +
        "public void M(){" +
        " Console.Write(123);" +
        "}}";
    var syntaxTree = CSharpSyntaxTree.ParseText(sourceText);
    
    var globalUsings = File.ReadAllText("Microsoft.NET.Sdk.usings.cs");
    var usingsTree = CSharpSyntaxTree.ParseText(globalUsings);
    
    var coreReferences =
        ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES"))
        .Split(Path.PathSeparator)
        .Select(p => MetadataReference.CreateFromFile(p));
    var compilation = CSharpCompilation.Create("MyAnalysis")
        .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
        .AddReferences(coreReferences)
        .AddSyntaxTrees(usingsTree, syntaxTree);
    
    var diagnostics = compilation.GetDiagnostics();
    Debug.Assert(!diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error));
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.