Namespaces are domain type names which makes it easier to find files and also it avoid name conflicts. They are independent of assemblies, which are units of deployment such as an .exe or .dll file.

The namespace keyword defines a namespace for types within that block

namespace Outer.Middle.Inner
class Class1 {}
class Class2 {}

the dots in the namespace indicate a hierarchy of nested namespace.

using Directive

The using directive imports a namespace.

using static (C#6)

Can import specific type with using static directive and all static members of that type can be used.

using static System.Console;

class Test
   static void Main() 
      WriteLine ("Hello");

The using static directive imports all accessible static members of the type, including fields, properties and nested types

You can also apply this directive to enum types using static System.Windows.Visibility;

var textBox = new TextBox { Visibility = Hidden ;}

Rules Within a Namespace

  1. Name scoping
    Names declared in outer namespace can be used unqualified within inner namespace. If you want to refer to a type in a different branch of your namespace hierarchy, you can use a partially qualified name.
  2. Name hiding
    If the same type name appears in both an inner and an outer namespace, the inner name wins.
  3. Repeated namespaces
    You can repeat a namespace declaration, as long as the type names within the namespaces don’t conflict
  4. Nested using directive
    You can nest a using directive within a namespace. This allows you to scope the using directive within a namespace declaration.
  5. Aliasing Types and Namespaces
    You can import just the specific types you need, giving each type an alias

Advanced Namespace Features

  1. Extern
    Extern aliases allow your program to reference two types with the same fully qualified name
  2. Namespace alias qualifiers
    Names in inner namespaces hide names in outer namespaces.

Leave a Reply

Your email address will not be published. Required fields are marked *