Home

Namespaces

   

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.

 

ApplicationApplication: Introducing Namespaces

  1. Start Microsoft Visual Studio
  2. To create a new project, on the main menu, click File -> New Project
  3. In the left list, click Windows
  4. In the right list, click Empty Project
  5. Change the name to DepartmentStore4
  6. Click OK
  7. To create a new file, on the main menu, click Project -> Add New Item...
  8. In the left list, click Code
  9. In the right list, click Code File
  10. Change the Name to DepartmentStore and press Add
  11. In the empty document, type the following:
    public class DepartmentStore
    {
        static int Main()
        {
            return 0;
        }
    }

Manually Creating a Namespace

To create a namespace:

  • Type code that starts with the namespace keyword followed by the name of the section
  • Right-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

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
    {
    }
}

ApplicationApplication: Creating a Namespace

  • To create a namespace, change the document as follows:
    public class DepartmentStore
    {
        static int Main()
        {
            return 0;
        }
    }
    
    namespace Store
    {
        public class StoreItem
        {
            public int itemNumber;
            public string itemName;
            public decimal unitPrice;
        }
    }

An Automatically Generated Namespace

In Lesson 5, we mentioned that, to create a new class:

  • On the main menu, you can click Project -> Add Class...
  • In the Solution Explorer, you can right-click the name of the project -> Add -> click Class...
  • In the Class View, you can right-click the name of the Project -> Add -> Class...

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

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

ApplicationApplication: Accessing Members of a Namespace

  1. To access the content of a namespace, change the document as follows:
    public class DepartmentStore
    {
        static int 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.

ApplicationApplication: 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 int 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.

ApplicationApplication: Using Namespaces

  1. To use the using keyword, change the document as follows:
    using Supply;
    using Store;
    
    public class DepartmentStore
    {
        static int 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
{
    public 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;
    }
}

ApplicationApplication: 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 int 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 a generic and the other not. Here is an example:

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

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

ApplicationApplication: 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 int 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.

ApplicationApplication: 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 int 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:

  • Click above the section of code, type namespace followed by a name and {. Locate the end of the section and type }
  • Select the code that you want to include in a namespace. Right-click the selection and click Surround With... In the list, double-click namespace

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:

  • In the Code Editor, locate its name and change it. Then click the arrow of its tag and choose an option from the menu
     
    Rename
  • Right-click the name and click Rename... Then follow the dialog boxes as we have reviewed already

Introduction to Built-In Namespaces

 

The Object Browser

The .NET Framework is a very rich, powerful, and expanded library. Its primary power is in its large set of classes. To organize these classes, the .NET Framework provides many namespaces. Each namespace is used to provide a specific set of classes.

To help you examine the namespaces of the .NET Framework, Microsoft Visual Studio provides the Object Browser. To access it

  • On the main menu, click View -> Object Browser
  • On the Standard toolbar, click the Object Browser button Object Browser
  • Press F2

The Object is made of three frames:

Object Browser

The left frame shows a list of libraries. Notice that some nodes show a series of numbers between square brackets. This represents the version of the .NET Framework. When different nodes with the same name have square brackets, it means the library has been created or updated in different versions. For example, 4.0.0.0 represents Microsoft .NET Framework 4.0

Because most libraries contain more than one namespace, each node is equipped with a + button. To expand a node, click the + button. After expanding a library, the namespaces it contain appear as nodes. Because most namespaces contain more than one class, each namespace is equipped with a + button. To expand it, you can click the + button. After expanding a namespace, its list of classes appear. To show the members of a class, in the left frame, click it:

Object Browser

To get an explanation or description of a member of the class, in the top-right frame, click that member. The bottom-right frame presents some information about the selected item.

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 int 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 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".

.NET Data Types

All of the data types we have used so far are represented by classes in the .NET Framework. This means that 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 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.

Because the data types are defined as classes, they are equipped with methods. One of the methods that each one of them has is called ToString. As its name implies, it is used to convert a value to a string.

ApplicationApplication: Ending the Lesson

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

Previous Copyright © 2010-2016, FunctionX Next