Namespaces

In this part of the C# tutorial, we will describe namespaces.

Namespaces are used to organize code at the highest logical level. They classify and present programming elements that are exposed to other programs and applications. Within a namespace, we can declare another namespace, a class, an interface, a structure, an enumeration or a delegate. We cannot define items such as properties, variables and events. These items must be declared within containers such as structures or classes. Namespaces prevent ambiguity and simplify references when using large groups of objects such as class libraries.

Namespaces organize objects in an assembly. An assembly is a reusable, versionable and self-describing building block of a CLR application. Assemblies can contain multiple namespaces. Namespaces can contain other namespaces. An assembly provides a fundamental unit of physical code grouping. A namespace provides a fundamental unit of logical code grouping.

public class CSharpApp
{
    static void Main()
    {
        System.Console.WriteLine("Simple namespace example");
    }
}

The built-in libraries are organized within namespaces. Take the Console class. It is available within the System namespace. To call the static WriteLine() method of the Console class, we use its fully qualified name. Fully qualified names are object references that are prefixed with the name of the namespace where the object is defined.

In the following code, we have two files that share the same namespace.

namespace2.cs
using System;

namespace ZetCode
{
    public class Example
    {
        public int x = 0;
        
        public void Raise()
        {
            x += 100;
            Console.WriteLine(x);
        } 
    }
}

We have a ZetCode namespace. In the namespace, we have an Example class.

namespace ZetCode
{
...
}

We declare a namespace called ZetCode. The code goes inside the curly brackets of the ZetCode namespace.

namespace1.cs
namespace ZetCode
{
    public class CSharpApp
    {
        static void Main()
        {
            Example ex = new Example();
            ex.Raise();
            ex.Raise();
        }
    }
}

In the second file, we work with the Example class from the previous file. We invoke its Raise() method.

namespace ZetCode

We work in the same namespace.

Example ex = new Example();
ex.Raise();
ex.Raise();

We create an instance of the Example class. We call its Raise() method twice. Because we work with objects of the same namespace, we do not need to specify its name explicitly.

$ dmcs namespace1.cs namespace2.cs
$ ./namespace1.exe 
100
200

This is the example output.

The following code example has two distinct namespaces. We use the using keyword to import elements from a different namespace.

distinctnamespace2.cs
namespace MyMath
{
    public class Basic
    {
        public static double PI = 3.141592653589;
        
        public static double GetPi()
        {
            return PI;
        } 
    }
}

We have a skeleton of a Math class in a MyMath namespace. In the Basic class, we define a PI constant and a GetPi() method.

distinctnamespace1.cs
using MyMath;
using System;

namespace ZetCode
{
    public class CSharpApp
    {
        static void Main()
        {
            Console.WriteLine(Basic.PI);
            Console.WriteLine(Basic.GetPi());
        }
    }
}

In this file, we use the elements from the MyMath namespace.

using MyMath;

We import the elements from the MyMath namespace into our namespace.

Console.WriteLine(Basic.PI)
Console.WriteLine(Basic.GetPI())

Now we can use those elements. In our case it is the Basic class.

$ dmcs distinctnamespace1.cs distinctnamespace2.cs
$ ./distinctnamespace1.exe 
3.141592653589
3.141592653589

We compile the two files and run the program.

Root namespace

The root namespace is the mainspace of the .NET Framework libraries. It may happen that someone creates a type or a namespace that will conflict with ones from the .NET Framework. In such cases, we can refer to the root namespace with the global:: prefix.

namespace ZetCode
{
    class System 
    {
        public override string ToString() 
        {
            return "This is System class";
        }
    }

    public class RootNamespace
    {
        static void Main()
        {
            System s = new System();
            global::System.Console.WriteLine(s); 
        }
    }    
}

In our ZetCode namespace, we create a System class that will clash with the one from the .NET Framework.

System s = new System();

Here we refer to the System class from the ZetCode namespace.

global::System.Console.WriteLine(s); 

With the global:: prefix, we point to the System class of the root namespace.

The root namespace is also the default namespace for C# programs. In most programs in this tutorial, we did not specify any namespace. Such programs are added to the unnamed default namespace.

using System;

struct Book 
{
    public override string ToString()
    {
        return "Book struct in a default namespace";
    }
}

namespace MainProgram
{
    struct Book 
    {
        public override string ToString()
        {
            return "Book struct in a MainProgram namespace";
        }
    }

    public class DefaultNamespace
    {
        static void Main()
        {
            Book book1;
            global::Book book2;

            Console.WriteLine(book1);
            Console.WriteLine(book2);
        }
    }
}

We have two Book structures; one is defined in the MainProgram namespace, the other is defined outside this namespace.

struct Book 
{
    public override string ToString()
    {
        return "Book struct in a default namespace";
    }
}

This Book structure is defined outside of the custom named MainProgram namespace. It belongs to the default namespace.

Book book1;

We refer to the structure defined inside the MainProgram namespace.

global::Book book2;

With the global:: prefix we point to the structure defined outside the MainProgram namespace.

$ ./default.exe 
Book struct in a MainProgram namespace
Book struct in a default namespace

This is the output of the default.exe program.

Aliases

The using keyword can be used to create an alias for a namespace. With nested namespaces, the fully qualified names might get long. We can shorten them by creating aliases.

namespace ZetCode
{
    namespace Items
    {
        class Book 
        {
            public override string ToString()
            {
                return "This is a book";
            }
        }
    } 
}

namespace MainProgram
{
    using ZIB = ZetCode.Items.Book;

    public class Aliases
    {
        static void Main()
        {
            ZetCode.Items.Book book =  new ZetCode.Items.Book();
            ZIB book2 = new ZIB();
 
            System.Console.WriteLine(book);
            System.Console.WriteLine(book2);
        }
    }
}

In the example, we create an alias for a Book class that is enclosed by two namespaces.

namespace ZetCode
{
    namespace Items
    {
        class Book 
        {
        ...
        }
    } 
}

It is possible to nest a namespace into another namespace. The fully qualified name of the Book class is ZetCode.Items.Book.

using ZIB = ZetCode.Items.Book;

The using keyword createas a ZIB alias for the fully qualified name ZetCode.Items.Book.

ZetCode.Items.Book book =  new ZetCode.Items.Book();
ZIB book2 = new ZIB();

We use both names to create a book instance.

This part of the C# tutorial was dedicated to namespaces.