Skip to content

Adding an assembly attribute to a SourceFileTemplate moves its usings out of the namespace, so a relative using like Models stops resolving (CS0246) #196

Open

Description

@matt-edmondson

What's wrong

Since #148, AddSourceFile picks one of two layouts depending on whether the file has Attributes (SourceFileTemplate.cs#L66-L79):

  • With no attributes, the usings go inside the file-scoped namespace.
  • With attributes, the usings go at compilation-unit level, before the namespace.

C# resolves a using differently in those two places. Inside namespace Contoso.Widgets;, using Models; binds to Contoso.Widgets.Models (or Contoso.Models). At top level it only looks in the global namespace. So adding one unrelated [assembly: …] attribute changes what every using in the file binds to.

Reproduction

var f = new SourceFileTemplate { Namespace = "Contoso.Widgets", Usings = { "Models" } };
f.Classes.Add(new ClassTemplate { Name = "A", Keywords = { "public" }, Members = { new FieldTemplate { Type = "Widget", Name = "W", Keywords = { "public" } } } });

With Contoso.Widgets.Models.Widget in the project, this compiles. Now add f.Attributes.Add("assembly: System.CLSCompliant(true)"). The output becomes:

using Models;

[assembly: System.CLSCompliant(true)]

namespace Contoso.Widgets;
...

This fails with CS0246: The type or namespace name 'Models' could not be found, and Widget is not found either. Both versions were compiled with the .NET 10 SDK.

The error is the better outcome. If a global namespace with the same name exists, the using silently binds to that namespace instead. Nothing on SourceFileTemplate says that Usings resolve differently once Attributes is set. The <remarks> on AddSourceFile explain the ordering but not this consequence, and #143/#148 did not discuss it.

Suggested fix / acceptance criteria

At minimum, document on SourceFileTemplate.Usings and AddSourceFile that once Attributes is non-empty, usings are written outside the namespace and must be fully qualified.

Better, make the binding independent of whether attributes are present. Two options:

Either way:

  • Add a test that pins the chosen behaviour, ideally by compiling a file with a relative using both with and without an attribute.

Activity

  1. matt-edmondson commented on Nov 10, 2026

    @matt-edmondson
    ContributorAuthor

    Triage


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions