| Property | Value |
|---|---|
| Package | Philips.CodeAnalysis.MaintainabilityAnalyzers |
| Diagnostic ID | PH2006 |
| Category | Naming |
| Analyzer | NamespaceMatchFilePathAnalyzer |
| CodeFix | No |
| Severity | Error |
| Enabled By Default | Yes |
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:
In the default configuration, the path must include a folder that exactly matches the 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.
Ideally, use the more strict, non-default, configuration. Then consistently have the namespaces of all of your files match the folder structure.
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 |
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
{
}
}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.
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 |