Fundamentals of Namespaces

Introduction

A namespace is a section of code that is identified with a specific name. The name could be anything such as somebody's name, the name of the company's department, a city, etc.

Practical LearningPractical Learning: Introducing Namespaces

  1. Start Microsoft Visual Studio. In the Visual Studio 2019 dialog box, click Create a New Project (if Microsoft Visual Studio was already opened, on the main menu, click File -> New -> Project...)
  2. In the list of projects templates, click Empty Project (.NET Framework)
  3. Click Next
  4. Change the name to DepartmentStore2
  5. Click Create
  6. To create a new file, on the main menu, click Project -> Add New Item...
  7. In the left list under Visual C# Items, click Code
  8. In the right list, click Code File
  9. Change the Name to DepartmentStore
  10. Click Add
  11. In the empty document, type the following:
    public class DepartmentStore
    {
        static void Main()
        {
            
        }
    }

Manually Creating a Namespace

To create a namespace:

Like a class, the section that is part of a namespace starts with an opening curly bracket "{" and ends with a closing curly bracket "}". Here is an example:

namespace Business
{
}

Between the curly brackets, you can type anything that is part of the namespace. For example, you can create a class inside of a namespace. Here is an example:

namespace Business
{
    class House
    {
    }
}

Practical LearningPractical Learning: Creating a Namespace

Accessing the Members of a Namespace

After creating the necessary members of a namespace, you can use the period operator to access an item that is a membeer of the namespace. To do this, in the desired location, type the name of the namespace, followed by a period, followed by the desired member of the namespace. Here is an example:

namespace Business
{
    class House
    {
        public string PropertyNumber { get; set; }
        public double MarketValue { get; set; }
    }
}

class Exercise
{
    static void Main()
    {
        Business.House property = new Business.House();

        property.PropertyNumber = "D294FF";
        property.MarketValue = 425_880;
    }
}

Practical LearningPractical Learning: Accessing Members of a Namespace

  1. To access the content of a namespace, change the document as follows:
    public class DepartmentStore
    {
        static void Main()
        {
            FunDepartmentStore.StoreItem si = new FunDepartmentStore.StoreItem();
    
            si.ItemNumber = 613508;
            si.ItemName = "Merino Crew Neck Cardigan";
            si.UnitPrice = 80.00;
    
            System.Console.WriteLine("Store Inventory");
            System.Console.WriteLine("----------------------------------------");
            System.Console.Write("Item #:     ");
            System.Console.WriteLine(si.ItemNumber);
            System.Console.Write("Item Name:  ");
            System.Console.WriteLine(si.ItemName);
            System.Console.Write("Unit Price: ");
            System.Console.WriteLine(si.UnitPrice);
            System.Console.WriteLine("=======================================");
        }
    }
    
    namespace FunDepartmentStore
    {
        class StoreItem
        {
            public int ItemNumber { get; set; }
            public string ItemName { get; set; }
            public double UnitPrice { get; set; }
        }
    }
  2. To execute the application to see the result, on the main menu, click Debug -> Start Without Debugging. This would produce:
    Store Inventory
    ----------------------------------------
    Item #:     613508
    Item Name:  Merino Crew Neck Cardigan
    Unit Price: 80
    =======================================
    Press any key to continue . . .
  3. Press Enter and return to your programming environment

Creating and Using Many Namespaces

Introduction

In the above example, we created one namespace in a document. In the same way, you can create many namespaces in the same document, as long as the body of each namespace is appropriately delimited. Here is an example:

namespace RealEstate
{
    class House
    {
        public string PropertyNumber { get; set; }
        public double MarketValue { get; set; }
    }
}

namespace Dealership
{
    class Car
    {
    }
}

You can also create namespaces in various files. For example, you can create each namespace in its own file, or you can create a group of namespaces in one file and one or a group of namespaces in another file. After creating the files, to access the content of a namespace, you can qualify the name of the class.

Practical LearningPractical Learning: Creating Many Namespaces

  1. To create a new file, on the main menu, click Project -> Add New Item...
  2. If necessary, in the left list, click Code.
    In the right list, click Code File
  3. Change the Name to Records and press Add
  4. Change the document as follows:
    namespace FunDepartmentStore
    {
        class StoreItem
        {
            public int ItemNumber { get; set; }
            public string ItemName { get; set; }
            public double UnitPrice { get; set; }
        }
    }
  5. To create a new file, in the Solution Explorer, right-click DepartmentStore2 -> Add -> New Item...
  6. If necessary, in the left list, click Code.
    In the right list, click Code File
  7. Change the Name to Supplies and press Add
  8. Change the document as follows:
    namespace Supplies
    {
        class Manufacturer
        {
            public string CompanyName { get; set; }
            public string ContactName { get; set; }
            public string ContactPhone;
        }
    }
  9. Click the DepartmentStore.cs label to access its file
  10. To use the namespaces, change the document as follows:
    public class DepartmentStore
    {
        static void Main()
        {
            Supplies.Manufacturer dealer = new Supplies.Manufacturer();
            dealer.CompanyName = "Peel Corp";
            dealer.ContactName = "Sylvain Yobo";
            dealer.ContactPhone = "(602) 791-8074";
    
            FunDepartmentStore.StoreItem si = new FunDepartmentStore.StoreItem();
    
            si.ItemNumber = 613508;
            si.ItemName = "Merino Crew Neck Cardigan";
            si.UnitPrice = 80.00;
    
    
            System.Console.WriteLine("Manufacturer Information");
            System.Console.Write("Company Name:  ");
            System.Console.WriteLine(dealer.CompanyName);
            System.Console.Write("Contact Name:  ");
            System.Console.WriteLine(dealer.ContactName);
            System.Console.Write("Contact Phone: ");
            System.Console.WriteLine(dealer.ContactPhone);
            System.Console.WriteLine("=======================================");
    
            System.Console.WriteLine("Store Inventory");
            System.Console.WriteLine("---------------------------------------");
            System.Console.Write("Item #:     ");
            System.Console.WriteLine(si.ItemNumber);
            System.Console.Write("Item Name:  ");
            System.Console.WriteLine(si.ItemName);
            System.Console.Write("Unit Price: ");
            System.Console.WriteLine(si.UnitPrice);
            System.Console.WriteLine("=======================================");
        }
    }
  11. To execute the application to see the result, on the main menu, click Debug -> Start Without Debugging. This would produce:
    Manufacturer Information
    Company Name:  Peel Corp
    Contact Name:  Sylvain Yobo
    Contact Phone: (602) 791-8074
    =======================================
    Store Inventory
    ---------------------------------------
    Item #:     613508
    Item Name:  Merino Crew Neck Cardigan
    Unit Price: 80
    =======================================
    Press any key to continue . . .
  12. Press Enter and return to your programming environment

Using a Namespace

We saw that, to call an object or a method that is part of a namespace, you must "qualify" the object using the period operator. Instead of using this approach, if you already know the name of a namespace that exists or the namespace has been created in another file, you can use a special keyword to indicate that you are using a namespace that is defined somewhere. This is done with the using keyword. To do this, on top of the file (preferably), type using followed by the name of the namespace.

With the using keyword, you can include as many external namespaces as necessary.

Whether you use the using keyword or not, you can still access a member of a namespace by fully qualifying its name. In fact, when there is a name conflict (it's usually not a conflict; it could just be the way the namespace was created; a common example is in Visual Basic where the Switch() function sometimes conflicts with the Switch keyword), even if you use the using keyword, you must still qualify the name of the class.

Practical LearningPractical Learning: Using Namespaces

  1. To use the using keyword, change the document as follows:
    using Supplies;
    using FunDepartmentStore;
    
    public class DepartmentStore
    {
        static void Main()
        {
            Manufacturer dealer = new Manufacturer();
            dealer.CompanyName = "Peel Corp";
            dealer.ContactName = "Sylvain Yobo";
            dealer.ContactPhone = "(602) 791-8074";
    
            StoreItem si = new StoreItem();
    
            si.ItemNumber = 613508;
            si.ItemName = "Merino Crew Neck Cardigan";
            si.UnitPrice = 80.00;
    
    
            System.Console.WriteLine("Manufacturer Information");
            System.Console.Write("Company Name:  ");
            System.Console.WriteLine(dealer.CompanyName);
            System.Console.Write("Contact Name:  ");
            System.Console.WriteLine(dealer.ContactName);
            System.Console.Write("Contact Phone: ");
            System.Console.WriteLine(dealer.ContactPhone);
            System.Console.WriteLine("=======================================");
    
            System.Console.WriteLine("Store Inventory");
            System.Console.WriteLine("---------------------------------------");
            System.Console.Write("Item #:     ");
            System.Console.WriteLine(si.ItemNumber);
            System.Console.Write("Item Name:  ");
            System.Console.WriteLine(si.ItemName);
            System.Console.Write("Unit Price: ");
            System.Console.WriteLine(si.UnitPrice);
            System.Console.WriteLine("=======================================");
        }
    }
  2. To execute the project and see the result, on the main menu, click Debug -> Start Without Debugging
  3. Press Enter and return to your programming environment

Nesting a Namespace

The Introduction

You can create one namespace inside of another namespace. Creating a namespace inside of another is referred to as nesting the namespace. The namespace inside of another namespace is nested. To create a namespace inside of another, simply type it as you would create another namespace. Here is an example:

namespace Business
{
    class House
    {
        public string PropertyNumber { get; set; }
        public double MarketValue { get; set; }
    }

    namespace Dealership
    {
    }
}

In the example above, the Dealership namespace is nested inside of the Business namespace. After creating the desired namespaces, nested or not, you can create the necessary class(es) inside of the desired namespace.

To access anything that is included in a nested namespace, you use the period operator before calling a member of a namespace or before calling the next nested namespace. Here is an example:

namespace Business
{
    class House
    {
        public string PropertyNumber { get; set; }
        public double MarketValue { get; set; }
    }

    namespace Dealership
    {
        class Car
        {
            public double MarketValue { get; set; }
        }
    }
}

class Exercise
{
    static void Main()
    {
        Business.House property = new Business.House();

        property.PropertyNumber = "D294FF";
        property.MarketValue = 425880;

        Business.Dealership.Car vehicle = new Business.Dealership.Car();
        vehicle.MarketValue = 38425.50;
    }
}

In the same way, you can nest as many namespaces inside of other namespaces as you judge necessary.

Practical LearningPractical Learning: Nesting Namespaces

  1. Click the Records.cs label to access its document and change it as follows:
    namespace FunDepartmentStore
    {
        namespace Inventory
        {
            class StoreItem
            {
                public int ItemNumber { get; set; }
                public string ItemName { get; set; }
                public double UnitPrice { get; set; }
            }
        }
    
        namespace Personel
        {
            namespace PayrollRecords
            {
                class Employee
                {
                    public string FirstName { get; set; }
                    public string LastName { get; set; }
                    public double HourlySalary { get; set; }
                }
    
                class Contractors
                {
                    public string FullName { get; set; }
                    public int ContractStatus { get; set; }
                }
            }
        }
    }
  2. Access the DepartmentStore.cs file and change it as follows:
    using Supply;
    using Store.Inventory;
    
    class DepartmentStore
    {
        static void Main()
        {
            . . . No Change
    
            
        }
    }

Nesting a Namespace by Name

Another technique used to nest a namespace consists of starting to create one. Then, after its name, type a period followed by a name for the nested namespace. Here is an example:

namespace Geometry.Quadrilaterals
{
    
}

After creating the nested namespace, you can access its contents by qualifying it. Here is an example:

namespace Geometry.Quadrilaterals
{
    class Square
    {
        public double Side { get; set; }
    }
}

class Exercise
{
    static void Main()
    {
        Geometry.Quadrilaterals.Square sqr = new Geometry.Quadrilaterals.Square();

        sqr.side = 25.85;
    }
}

In the same way, you can nest other namespaces inside of one. Here are examples:

namespace Geometry.Quadrilaterals
{
    
}

namespace Geometry.Rounds
{
    
}

In the same way, you can create as many namespaces as necessary inside of others. After nesting a namespace, to access its content, you can qualify the desired name. Here is an example:

namespace Geometry.Quadrilaterals
{
    class Square
    {
        public double Side { get; set; }
    }
}

namespace Geometry.Volumes.Elliptic
{
    class Cylinder
    {
        public double Radius { get; set; }
    }
}

class Exercise
{
    static void Main()
    {
        Geometry.Quadrilaterals.Square sqr = new Geometry.Quadrilaterals.Square();
        Geometry.Volumes.Elliptic.Cylinder cyl = new Geometry.Volumes.Elliptic.Cylinder();

        sqr.side = 25.85;
        cyl.radius = 36.85;
    }
}

Class Overloading? No Way! Way...

Consider the following code that creates two classes in a single document:

class Number
{
    public int value;
}

class Number
{
    public int integral;
    public int precision;
}

This code will produce an error. This is because you cannot create two or more classes directly in a document if those classes use the same name. This means that you cannot overload the name of a class in a directly in a document. That is, you cannot have two classes with the same name in the same scope. One alternative is to put each class in its own namespace. Here is an example:

namespace Arithmetic
{
    class Numbers
    {
        public int value;
    }
}

namespace Algebra
{
    class Numbers
    {
        public int integral;
        public int precision;
    }
}

Practical LearningPractical Learning: Using a Commonly Named Class

  1. Access the Suppliers.cs file and change it as follows:
    namespace Supplies
    {
        class SalesPerson
        {
            public string FullName { get; set; }
            public string Expertise { get; set; }
            public string PhoneNumber { get; set; }
        }
    }
    
    namespace Manufacturers.Domestic
    {
        class Manufacturer
        {
            public string CompanyName { get; set; }
            public string ContactName { get; set; }
            public string ContactPhone { get; set; }
        }
    }
    
    namespace Manufacturers.Foreign.Asia
    {
        class Manufacturer
        {
            public string Country { get; set; }
            public string CompanyName { get; set; }
            public string ContactName { get; set; }
            public string ContactPhone { get; set; }
            public string WebSite { get; set; }
        }
    }
  2. Click the DepartmentStore.cs tab and change its document as follows:
    using Supply;
    using Manufacturers.Foreign.Asia;
    using Store.Inventory;
    
    class DepartmentStore
    {
        static void Main()
        {
            . . . No Change
    
            
        }
    }

The Alias of a Namespace

If you have to access a namespace that is nested in another namespace, that too is nested, that is also nested, etc, the access can be long. As an alternative, you can create a shortcut that makes it possible to access a member of the nested namespace with a shorter label. That shortcut is called an alias. To create an alias for a namespace, in the top section where the inside member is needed, type using, followed by the desired name, followed by =, followed by the complete namespace. After doing this, you can then use the alias in place of the namespace.

Practical LearningPractical Learning: Creating and Using an Alias

  1. Access the DepartmentStore.cs file and change it as follows:
    using Supplies;
    using FunDepartmentStore.Personel;
    using FunDepartmentStore.Inventory;
    using Asian = Manufacturers.Foreign.Asia;
    
    public class DepartmentStore
    {
        static void Main()
        {
            Asian.Manufacturer dealer = new Asian.Manufacturer();
            dealer.CompanyName = "Peel Corp";
            dealer.ContactName = "Sylvain Yobo";
            dealer.ContactPhone = "(602) 791-8074";
    
            StoreItem si = new StoreItem();
    
            si.ItemNumber = 613508;
            si.ItemName = "Merino Crew Neck Cardigan";
            si.UnitPrice = 80.00;
    
            System.Console.WriteLine("Manufacturer Information");
            System.Console.Write("Company Name:  ");
            System.Console.WriteLine(dealer.CompanyName);
            System.Console.Write("Contact Name:  ");
            System.Console.WriteLine(dealer.ContactName);
            System.Console.Write("Contact Phone: ");
            System.Console.WriteLine(dealer.ContactPhone);
            System.Console.WriteLine("=======================================");
    
            System.Console.WriteLine("Store Inventory");
            System.Console.WriteLine("---------------------------------------");
            System.Console.Write("Item #:     ");
            System.Console.WriteLine(si.ItemNumber);
            System.Console.Write("Item Name:  ");
            System.Console.WriteLine(si.ItemName);
            System.Console.Write("Unit Price: ");
            System.Console.WriteLine(si.UnitPrice);
            System.Console.WriteLine("=======================================");
        }
    }
  2. To execute the application to see the result, on the main menu, click Debug -> Start Without Dubbing
  3. Press any key to close the DOS window and return to your programming environment

Namespaces and Inheritance

Imagine you had created a class named Element in a namespace named Chemistry as follows:

namespace Chemistry
{
    class Element
    {
    }
}

To derive a class from a class that belongs to a namespace, type the name of the namespace, followed by the period operator ".", and followed by the name of the base namespace. Here is an example:

namespace Chemistry
{
    class Element
    {
    }
}

class Isotope : Chemistry.Element
{
    public int NeutronNumber { get; set; }
}

If you need to call the class that was defined in a different namespace, you can qualify its name with the period operator. Here is an example:

namespace Chemistry
{
    class Element
    {
    }
}

class Isotope : Chemistry.Element
{
    public int NeutronNumber { get; set; }
}

class Exercise
{
    public void Create()
    {
	    Chemistry.Element h = new Chemistry.Element();
    }
}

Alternatively, to use the contents of a namespace, prior to calling a member of that namespace, you can type the using keyword followed by the name of the namespace. Here is an example:

using Chemistry;

class Isotope : Element
{
    public int NeutronNumber { get; set; }
}

class Exercise
{
    public void Create()
    {
	    Element h = new Element();
    }
}

Consider the following class named Matter and that is created in a nested namespace:

namespace Chemistry
{
    class Element
    {
    }

    namespace Atoms
    {
        namespace Nucleons
        {
            class Proton
            {
                public string Symbol { get; set; }
            }

            class Neutron
            {
            }
        }

        public class Matter
        {
            public double Mass { get; set; }
        }
    }
}

If you want to create a class that is based on a class in a nested namespace, you can qualify its name. Here is an example:

class Atom : Chemistry.Atoms.Matter
{
    public Chemistry.Element Element { get; set; }
    public Nucleus Nucleus { get; set; }
}

Public Classes and Namespaces

When you create a class in a namespace, you can mark that class with an access level, such as public. The rules are the same for a public class as we saw in the presvious lesson. You just have to remember that the class is a member of the namespace. Here is an example:

namespace AltairRealtors
{
    public class House
    {
        public string PropertyType{ get; set; }
        public int    Bedrooms    { get; set; }
        public double MarketValue { get; set; }
    }
}

Partial Classes and Namespaces

When creating a class that is partial, you can make it a member of a namespace. There is no particular rule to follow, as long as you keep in mind that the class is a member of a namespace. Here is an example:

namespace NationalCensus
{
    partial class Person
    {
        public string FirstName { get; set; }
        public string LastName  { get; set; }
    }
}

In the same way, a partial class can be created in a namespace. Here is an example:

namespace HighwaySystem
{
    public class Road
    {

    }

    public partial class Interstate : Road
    {
    }
}

A Namespace from Microsoft Visual Studio

Introduction the .NET Framework

As a simple way to create a namespace in Microsoft Visual Studio, rght-click the section where you want to create the namespace and double-click Insert Snippet... Double-click Visual C#. In the list, double-click namespace.

A Namespace from a Class

In Microsoft Visual Studio, to create a new class:

If you use any of these approaches, Microsoft Visual Studio would create a namespace using the name of the project and would add the new class to it.

A Namespace from a Project

Microsoft Visual Studio provides different templates you can use various types of project. Except for the empty projects, when you create a non-empty project, the studion adds one or more classes. Each class is created in a namespace. The namespace uses the name of the project.

Managing Namespaces

Inserting a Namespace

If you have existing code already, you can include it in a namespace. To do that:

Renaming a Namespace

You can manually rename a namespace or benefit from the assistance of the Code Editor. To rename a namespace:

An Automatically Generated Namespace

In Microsoft Visual Studio, to start a console project, in the Create a New Project dialog box, click Console App (.NET Core) or Console App (.NET Framework) and click Next. Give a name to the project and click Create. In this case, Microsoft Visual Studio would create a project and add a class that contains the Main() method. That class is created in a namespace that uses the same name as the project.

Besides the techniques we have used so far, to create a class in Microsoft Visual Studio:

In the middle list of the Add New Item dialog box, make sure Class is selected. Accept or change the Name of the class. Click Add. If you use any of these approaches, Microsoft Visual Studio would create a namespace using the name of the project and would add the new class to it.

Practical LearningPractical Learning: Introducing Namespaces

  1. To start a new project, on the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the Create a New Project dialog box, click All Languages and click C#
  3. In the list of project templates, click Empty Project (.NET Framework)
  4. Click Next
  5. Change the name to DepartmentStore3
  6. Click Create
  7. To start a new class, in the Solution Explorer, right-click DepartmentStore3, position the mouse on Add, and click Class...
  8. In the middle list of the Add New Item dialog box, make sure Class is selected.
    Change the Name to DepartmentStore
  9. Click Add
  10. Change the document as follows:
    namespace DepartmentStore3
    {
        class DepartmentStore
        {
            static void Main()
            {
                
            }
        }
    }

Practical LearningPractical Learning: Ending the Lesson

  1. Close your programming environment
  2. When asked whether you want to save, click No

Previous Copyright © 2001-2021, C# Key Next