This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
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 |
A public or protected type is defined outside the scope of a named namespace.
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.
To fix a violation of this rule, place the type in a namespace.
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.
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 tonone
in theconfiguration file.
[*.{cs,vb}]dotnet_diagnostic.CA1050.severity = none
For more information, seeHow to suppress code analysis warnings.
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 ClassNamespace ca1050 Public Class Test Public Overrides Function ToString() As String Return "Test lives in a namespace!" End Function End ClassEnd Namespace
The following application uses the library that was defined previously. The type that's declared outside a namespace is created when the nameTest
is not qualified by a namespace. To access theTest
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 SubEnd Class
Was this page helpful?
Was this page helpful?