Skip to content

Latest commit

 

History

History
99 lines (72 loc) · 2.96 KB

File metadata and controls

99 lines (72 loc) · 2.96 KB

PH2006: Namespace matches File Path

Property Value
Package Philips.CodeAnalysis.MaintainabilityAnalyzers
Diagnostic ID PH2006
Category Naming
Analyzer NamespaceMatchFilePathAnalyzer
CodeFix No
Severity Error
Enabled By Default Yes

Introduction

In order to prevent pollution of namespaces, the File Path and Namespace must match. Try enabling IDE0130 in lieu of this rule.

There are two modes:

Path contains folder that matches the Namespace (Default)

In the default configuration, the path must include a folder that exactly matches the namespace.

Path ends with Namespace

In this more strict mode, the namespace must exactly match the end of the file path. For the purposes of comparison, path separators are treated as dots in the namespace.

How to solve

Ideally, use the more strict, non-default, configuration. Then consistently have the namespaces of all of your files match the folder structure.

Exceptions

The following namespaces are always exempt from this rule. See supporting information for reasoning.

Namespace Justification
System.Runtime.CompilerServices Init setter support in .NET Standard 2.x

Example

If the file path is .\ConsoleApp\MyClass.cs then the following code will fail:

namespace NotConsoleApp
{
  public class MyClass
  {
  }
}

The corrected code is:

namespace ConsoleApp
{
  public class MyClass
  {
  }
}

If the file path is .\ConsoleApp\MyFolder\MyClass.cs then the following code will pass for the default mode but fail when folder_in_namespace = true:

namespace ConsoleApp
{
  public class MyClass
  {
  }
}

The correct code when folder_in_namespace = true (and incorrect code for the default mode) is:

namespace ConsoleApp.MyFolder
{
  public class MyClass
  {
  }
}

Configuration

To enable the more strict mode, add dotnet_code_quality.PH2006.folder_in_namespace = true to the .editorconfig. The general ways of suppressing diagnostics apply.

Similar Analyzers

See these analyzers for other rules related to namespaces:

ID Title
IDE0130 Namespace does not match folder structure
PH2079 Namespace uses predefined prefix
PH2131 Align filename and class name
PH2135 Namespace matches Assembly Name