CA1050: Declare types in namespaces
Property | Value |
---|---|
Rule ID | CA1050 |
Title | Declare types in namespaces |
Category | Design |
Fix is breaking or non-breaking | Breaking |
Enabled by default in .NET 9 | As suggestion |
Cause
A public or protected type is defined outside the scope of a named namespace.
Rule description
Types are declared in namespaces to prevent name collisions, and as a way to organize related types in an object hierarchy. Types that are outside any named namespace are in a global namespace that cannot be referenced in code.
How to fix violations
To fix a violation of this rule, place the type in a namespace.
When to suppress warnings
Although you never have to suppress a warning from this rule, it is safe to do this when the assembly will never be used together with other assemblies.
Suppress a warning
If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#pragma warning disable CA1050
// The code that's violating the rule is on this line.
#pragma warning restore CA1050
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1050.severity = none
For more information, see How to suppress code analysis warnings.
Example 1
The following example shows a library that has a type incorrectly declared outside a namespace, and a type that has the same name declared in a namespace.
// Violates rule: DeclareTypesInNamespaces.
using System;
public class Test
{
public override string ToString()
{
return "Test does not live in a namespace!";
}
}
namespace ca1050
{
public class Test
{
public override string ToString()
{
return "Test lives in a namespace!";
}
}
}
' Violates rule: DeclareTypesInNamespaces.
Public Class Test
Public Overrides Function ToString() As String
Return "Test does not live in a namespace!"
End Function
End Class
Namespace ca1050
Public Class Test
Public Overrides Function ToString() As String
Return "Test lives in a namespace!"
End Function
End Class
End Namespace
Example 2
The following application uses the library that was defined previously. The type that's declared outside a namespace is created when the name Test
is not qualified by a namespace. To access the Test
type that's declared inside a namespace, the namespace name is required.
public class MainHolder
{
public static void Main1050()
{
Test t1 = new Test();
Console.WriteLine(t1.ToString());
ca1050.Test t2 = new ca1050.Test();
Console.WriteLine(t2.ToString());
}
}
Public Class MainHolder
Public Shared Sub Main1050()
Dim t1 As New Test()
Console.WriteLine(t1.ToString())
Dim t2 As New ca1050.Test()
Console.WriteLine(t2.ToString())
End Sub
End Class