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, or a city.

Practical LearningPractical Learning: Introducing Namespaces

  1. Start Microsoft Visual Studio
  2. To create a new project, on the main menu, click File -> New -> Project...
  3. In the right list, click Empty Project (.NET Framework)
  4. Change the name to DepartmentStore3
  5. Click OK
  6. To create a new file, on the main menu, click Project -> Add New Item...
  7. In the left list, 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()
        {
            return 0;
        }
    }

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 part 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
{
    public class House
    {
        public string propertyNumber;
        public decimal price;
    }
}

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

        property.propertyNumber = "D294FF";
        property.Price = 425880;
    }
}

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()
        {
            Store.StoreItem si = new Store.StoreItem();
    
            si.itemNumber = 613508;
            si.itemName = "Merino Crew Neck Cardigan";
            si.unitPrice = 80.00M;
    
            System.Console.WriteLine("Store Inventory");
            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.ReadKey();
            return 0;
        }
    }
    
    namespace Store
    {
        public class StoreItem
        {
            public int itemNumber;
            public string itemName;
            public decimal unitPrice;
        }
    }
  2. Execute the application to see the result:
    Store Inventory
    Item #:     613508
    Item Name:  Merino Crew Neck Cardigan
    Unit Price: 80.00
  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 file. In the same way, you can create many namespaces in the same file, as long as the body of each namespace is appropriately delimited. Here is an example:

namespace RealEstate
{
    public class House
    {
        public string propertyNumber;
        public decimal price;
    }
}

namespace Dealership
{
    public 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 Store
    {
        public class StoreItem
        {
            public int itemNumber;
            public string itemName;
            public decimal unitPrice;
        }
    }
  5. To create a new file, on the main menu, click Project -> Add New Item...
  6. If necessary, in the left list, click Code.
    In the right list, click Code File
  7. Change the Name to Suppliers and press Add
  8. Change the document as follows:
    namespace Supply
    {
        public class Manufacturer
        {
            public string companyName;
            public string contactName;
            public string contactPhone;
        }
    }
  9. To access the other file, click the DepartmentStore.cs label
  10. To use the namespaces, change the document as follows:
    public class DepartmentStore
    {
        static void Main()
        {
            Supply.Manufacturer dealer = new Supply.Manufacturer();
            dealer.companyName = "Peel Corp";
            dealer.contactName = "Sylvain Yobo";
            dealer.contactPhone = "(602) 791-8074";
    
            Store.StoreItem si = new Store.StoreItem();
    
            si.itemNumber = 613508;
            si.itemName = "Merino Crew Neck Cardigan";
            si.unitPrice = 80.00M;
    
            System.Console.WriteLine("Store Inventory");
            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.ReadKey();
            return 0;
        }
    }

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 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 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 using, 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 Supply;
    using Store;
    
    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.00M;
    
            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.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("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
    
            System.Console.ReadKey();
            return 0;
        }
    }
  2. Execute the application to see the result:
    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.00
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  3. Press Enter and return to your programming environment

Nesting a Namespace

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
{
    public class House
    {
        public string propertyNumber;
        public decimal price;
    }

    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
{
    public class House
    {
        public string propertyNumber;
        public decimal price;
    }

    namespace Dealership
    {
        public class Car
        {
            public decimal price;
        }
    }
}

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

        property.propertyNumber = "D294FF";
        property.price = 425880;

        Business.Dealership.Car vehicle = new Business.Dealership.Car();
        vehicle.price = 38425.50M;

    }
}

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

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
{
    public class Square
    {
        public double side;
    }
}

public class Exercise
{
    public 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
{
    public class Square
    {
        public double side;
    }
}

namespace Geometry.Volumes.Elliptic
{
    public class Cylinder
    {
        public double radius;
    }
}

public 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;
    }
}

Practical LearningPractical Learning: Nesting Namespaces

  1. Click the Records.cs label to access its document and change it as follows:
    namespace Store
    {
        namespace Inventory
        {
            public class StoreItem
            {
                public int itemNumber;
                public string itemName;
                public decimal unitPrice;
            }
        }
    
        namespace Personel
        {
            namespace PayrollRecords
            {
                public class Employee
                {
                    public string firstName;
                    public string lastName;
                    public decimal HourlySalary;
                }
    
                public class Contractors
                {
                    public string FullName;
                    public int ContractStatus;
                }
            }
        }
    }
  2. Access the DepartmentStore.cs file and change it as follows:
    using Supply;
    using Store.Inventory;
    
    public class DepartmentStore
    {
        static void Main()
        {
            . . . No Change
    
            return 0;
        }
    }

Class Overloading? No Way! Way

Unlike the methods of a class, you cannot overload the name of a class in a file. 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
{
    public class Numbers
    {
        public int value;
    }
}

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

Another alternative will be available when we study generics. That is, in the same namespace, one of the classes can be generic and the other not. Here is an example:

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

    public class Numbers<T>
    {
        public int value;
    }
}

Practical LearningPractical Learning: Using a Commonly Named Class

  1. Access the Suppliers.cs file and change it as follows:
    namespace Supply
    {
        public class SalesPerson
        {
            public string fullName;
            public string expertise;
            public string phoneNumber;
        }
    }
    
    namespace Manufacturers.Domestic
    {
        public class Manufacturer
        {
            public string companyName;
            public string contactName;
            public string contactPhone;
        }
    }
    
    namespace Manufacturers.Foreign.Asia
    {
        public class Manufacturer
        {
            public string country;
            public string companyName;
            public string contactName;
            public string contactPhone;
            public string webSite;
        }
    }
  2. Access the DepartmentStore.cs file and change it as follows:
    using Supply;
    using Manufacturers.Foreign.Asia;
    using Store.Inventory;
    
    public class DepartmentStore
    {
        static void Main()
        {
            . . . No Change
    
            return 0;
        }
    }

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 Supply;
    using Asian = Manufacturers.Foreign.Asia;
    using Store.Inventory;
    
    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.00M;
    
            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.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("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
    
            System.Console.ReadKey();
            return 0;
        }
    }
  2. Execute the application to see the result
  3. Close the DOS window and return to your programming environment

Managing Namespaces

Inserting a Namespace

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

Renaming a Namespace

Renaming a namespace follows the same logic we reviewed for variables, classes, and methods: you can manually rename it 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 middle frame of the New Project dialog box, click Console App (.NET Framework), give a name to the project and click OK. 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 middle list of the New Project dialog box, click Empty Project (.NET Framework)
  3. Change the name to DepartmentStore4
  4. Click OK
  5. Click the Class View tab to activate it
  6. To start a new class, in the Class View, right-click DepartmentStore4, position the mouse on Add, and click Class...
  7. In the middle list of the Add New Item dialog box, make sure Class is selected.
    Change the Name to DepartmentStore
  8. Click Add
  9. Change the document as follows:
    namespace DepartmentStore4
    {
        class DepartmentStore
        {
            public static int Main()
            {
                return 0;
            }
        }
    }

Introduction to Built-In Namespaces

Introduction to the System Namespace

The most regularly used namespace in the .NET Framework is called System. So far, to use the System namespace, we typed it inside a method. Here is an example:

public class Exercise
{
    static void Main()
    {
        System.Console.WriteLine("The wonderful world of C# programming");

        return 0;
    }
}

You can also precede System with global and the :: operator. Here is an example:

public class Exercise
{
    static int Main()
    {
        global::System.Console.WriteLine("The wonderful world of C# programming");

        return 0;
    }
}

We learned that, to access a namespace, you can use the using keyword. In the same way, you can use using to refer to the System namespace. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        System.Console.WriteLine("The wonderful world of C# programming");

        return 0;
    }
}

This time too, you can precede System with global::

using global::System;

public class Exercise
{
    static int Main()
    {
        System.Console.WriteLine("The wonderful world of C# programming");

        return 0;
    }
}

Once you have used using System or using global::System, you can use or omit System in the body of the function. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        Console.WriteLine("The wonderful world of C# programming");

        return 0;
    }
}

Introduction to the System.Windows.Forms Namespace

In most operating systems, including Microsoft Windows, a window is a shaped object that displays on the computer screen. Examples of objects are dialog boxes, Windows controls (such as buttons, combo boxes, scroll bars, toolbars, menus, etc), etc. Such objects are put together to get what is called a computer program or application. To support the ability to create an application that has Windows objects, the .NET Framework provides an assembly named System.Windows.Forms.dll. That assembly contains many namespaces. The most popular or most common used is the System.Windows.Forms namespace. That namespace contains the classes of most objects considered as Windows controls.

Introduction to Other Namespaces

The .NET Framework provides an incredibly long list of namespaces. We cannot review all of them now. Eventually, when we have to use a class, we will indicate in which namespace it exists.

As mentioned already, we saw in Lesson 5 that we could create a new class using the Add New Class option from the main menu, the Solution Explorer, or the Class View. If you use one of those techniques, the studio will also add other namespaces. For now, we will accept that code "as is".

Introduction to .NET Data Types

Overview

All of the data types we have used so far are represented by classes in the .NET Framework. As a result, they are equipped with methods. These classes are defined in the System namespace. The classes of these data types are defined as:

C# Data Type Equivalent .NET Class C# Data Type Equivalent .NET Class
bool Boolean char Char
byte Byte sbyte SByte
short Int16 ushort UInt16
int Int32 uint UInt32
long Int64 ulong UInt64
float Single   double Double
decimal Decimal      

This means that, if you don't want to use the data types we have reviewed so far, you can use the equivalent class that is defined in the System namespace. To use one of those classes, type its name. Here is an example:

class Operations
{
    public double Addition()
    {
		Double a;
		Double b;
		Double c;
		
		a = 128.76;
		b = 5044.52;
		c = a + b;

		return c;
    }
}

Because the regular names of data types we introduced in the previous lessons are more known and familiar, we will mostly use them.

Introduction to Converting a Value to a String

One of the methods that each class of the .NET types uses is called ToString. As its name implies, it is used to convert a value to a string. To convert the value of a variable to a string, call ToString on the variable. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        double hourlySalary = 14.50;
        string strWages = hourlySalary.ToString();

        Console.Write("Hourly Salary: ");
        Console.WriteLine(strWages);

        return 0;
    }
}

You can also call ToString directly on a constant value. You can also call it on an expression. Here are examples:

using System;

public class Exercise
{
    static void Main()
    {
        string strTimeWorked = 42.ToString();
        string strHourlySalary = 14.50.ToString();
        string strWeeklySalary = (42 * 14.50).ToString();

        Console.Write("Hourly Salary: ");
        Console.WriteLine(strHourlySalary);
        Console.Write("Time Worked: ");
        Console.WriteLine(strTimeWorked);
        Console.Write("Weekly Wages: ");
        Console.WriteLine(strWeeklySalary);

        return 0;
    }
}

Practical LearningPractical Learning: Ending the Lesson

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

Previous Copyright © 2001-2019, FunctionX Next