Declare types in namespaces

TypeName

DeclareTypesInNamespaces

CheckId

CA1050

Category

Microsoft.Design

Breaking Change

Breaking

Cause

A public or protected type is defined outside the scope of a named namespace.

Rule Description

Types are declared within namespaces to prevent name collisions, and as a way of organizing related types in an object hierarchy. Types 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

While it is never necessary to suppress a warning from this rule, it is safe to do this when the assembly will never be used with other assemblies.

Example

The following example shows a library with a type incorrectly declared outside a namespace, and a type with the same name declared in a namespace.

Imports System 

' 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 GoodSpace  

    Public Class Test 

        Public Overrides Function ToString() As String             
            Return "Test lives in a namespace!"         
        End Function   

    End Class  

End Namespace
using System;

// Violates rule: DeclareTypesInNamespaces. 
public class Test
{
   public override string ToString()
   {
      return "Test does not live in a namespace!";
   }
}

namespace GoodSpace
{
   public class Test
   {
      public override string ToString()
      {
         return "Test lives in a namespace!";
      }
   }
}   

The following application uses the library defined previously. Note that the type declared outside a namespace is created when the name Test is not qualified by a namespace. Note also that to access the Test type in Goodspace, the namespace name is required.

Imports System

Namespace ApplicationTester

    Public Class MainHolder

        Public Shared Sub Main()
            Dim t1 As New Test()
            Console.WriteLine(t1.ToString())

            Dim t2 As New GoodSpace.Test()
            Console.WriteLine(t2.ToString())
        End Sub 

    End Class 

End Namespace
using System;

namespace ApplicationTester
{
    public class MainHolder
    {
        public static void Main()
        {
            Test t1 = new Test();
            Console.WriteLine(t1.ToString());

            GoodSpace.Test t2 = new GoodSpace.Test();
            Console.WriteLine(t2.ToString());
        }
    }
}