0

I want to set a rule in .editorconfig so that all C# files where namespace is not explicitly set should render an error.

I've added these:

  • dotnet_diagnostic.IDE0130.severity = error # Namespace does not match folder structure
  • dotnet_diagnostic.IDE0161.severity = error # Namespace declaration preferences (prefer file-scoped)
  • csharp_style_namespace_declarations = file_scoped:error

Namespace is validated to follow file structure.

Screenshot IDE0130

And to be file scoped

Screenshot IDE0161

But if I remove the namespace altogether, I get no validation error.

4
  • 1
    Out of interest, why would you want to prevent file-scoped namespaces? That does explicitly set a namespace, so what do you object to about it? (Personally I love getting rid of completely unnecessary level of indentation...) Commented 18 hours ago
  • Not sure I understand, here is what I want to achieve: 1. All C# should have a namspace set explicitly (i.e. not possible to have a C# file missing namespace declaration) 2. All namespace declarations should be file scoped 3. All namespaces should match file structure With the current setup I solve 2 and 3, but not 1. Commented 17 hours ago
  • I think I'd misinterpreted the option - ignore me. (As for a solution to the actual problem - I'm not sure there's anything in editorconfig for this, but you could write your own Roslyn analyzer easily enough, or just a unit test which you could reuse across assemblies.) Commented 17 hours ago
  • Ok, it's for a client I'm working for and if I'd do that I'd need to justify the extra setup needed to achieve this "nice to have". So should there be no built-in way to do this check, I'll probably skip it. Commented 17 hours ago

1 Answer 1

0

Based on the comment from Jon Skeet that this probably is not possible with editorconfig, I wrote a generic unit test for it.

using System.Text.RegularExpressions;
using Shouldly;

namespace Base.SharedTests.UnitTests;

public partial class CodeTests
{
    [Fact]
    public void AllFiles_WithCsExtension_ShouldHaveFileScopedNamespaces()
    {
        var solutionBasePath = Path.GetFullPath(
            Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..")
        );

        var files = Directory
            .GetFiles(solutionBasePath, "*.cs", SearchOption.AllDirectories)
            .Where(f => !f.EndsWith("GlobalUsings.cs", StringComparison.Ordinal))
            .Where(f => !f.EndsWith("Program.cs", StringComparison.Ordinal))
            .Where(f => !f.Contains("/bin/", StringComparison.Ordinal))
            .Where(f => !f.Contains("/obj/", StringComparison.Ordinal));

        List<(string FileName, bool Result)> results =
        [
            .. files.Select(f =>
            {
                var text = File.ReadAllText(f);
                var fileName = Path.GetFileName(f);
                var result = NamespaceRegex().IsMatch(text);

                return (fileName, result);
            }),
        ];

        results.ShouldAllBe(r => r.Result == true);
    }

    [GeneratedRegex(@"^\s*namespace\s+[A-Za-z0-9_.]+\s*;", RegexOptions.Multiline)]
    private static partial Regex NamespaceRegex();
}
Sign up to request clarification or add additional context in comments.

1 Comment

I wouldn't check the files - I'd check the types in the assembly. That way you don't have to find the source files, or parse any C# code. You may need to exclude any "extra" types generated by the compiler though - they may have <> in the name, but you could see if you tried it...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.