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 and create a new Console App that supports .NET 8.0 (Long-Term Support) named PieceWork3
  2. To create a new file, on the main menu, click Project -> Add New Item...
  3. In the middle list, make sure Code File is selected
  4. Change the Name to Driver
  5. Click Add
  6. In the empty document, type the following:
    public class Driver
    {
        public string first_name;
        public string last_name;
    }
  7. To create a new file, on the main menu, click Project -> Add New Item...
  8. In the middle list, make sure Code File is selected
  9. Change the Name to Truck
  10. Click Add
  11. In the empty document, type the following:
    /* Piecework is the type of work that is paid on the number 
     * of items produced, the distance driven, etc.
     * In this exercise, a business uses trucks driven by some 
     * employees or contractors to deliver some products. 
     * The drivers are paid based on the distance they travel to 
     * deliver one or many products. */
    public class Truck
    {
        public string make;
        public string model;
    }
  12. To create a new file, on the main menu, click Project -> Add New Item...
  13. In the left list under Visual C# Items, click Code
  14. In the middle list, make sure Code File is selected.
    Change the Name to PieceDelivery
  15. Click Add
  16. In the empty document, type the following:
    using static System.Console;
    
    int miles;
    double pieceworkRate;
    
    WriteLine("===========================================================");
    WriteLine(" - Piece Work Delivery -");
    WriteLine("===========================================================");
    
    Truck trk = new Truck();
    
    WriteLine("You must provide the information about the truck");
    Write("Make:              ");
    trk.make = ReadLine();
    Write("Model:             ");
    trk.model = ReadLine();
    WriteLine("-----------------------------------------------------------");
    
    Driver drv = new Driver();
    
    WriteLine("You must provide the information about the truck driver");
    Write("First Name:        ");
    drv.first_name = ReadLine();
    Write("Last Name:         ");
    drv.last_name = ReadLine();
    WriteLine("-----------------------------------------------------------");
    
    WriteLine("Enter the values for the delivery");
    Write("Miles Driven:      ");
    miles = int.Parse(ReadLine());
    Write("Piecework Rate:    ");
    pieceworkRate = double.Parse(ReadLine());
    
    WriteLine("===========================================================");
    WriteLine(" - Piece Work Delivery -");
    WriteLine("===========================================================");
    WriteLine("Driver:            " + drv.first_name + " " + drv.last_name);
    WriteLine("Truck Details:     " + trk.make + " " + trk.model);
    WriteLine("-----------------------------------------------------------");
    WriteLine("Miles Driven:      {0}", miles);
    WriteLine("Piecework Rate:    {0}", pieceworkRate);
    WriteLine("Gross Salary:      {0}", miles * pieceworkRate);
    WriteLine("===========================================================");
  17. To execute, on the main menu of Microsoft Visual Studio, click Debug -> Start Without Debugging
  18. When requested, type the Make as Chevrolet and press Enter
  19. For the Model, type 3500 Express 4x2 and press Enter
  20. For the First Name, type Robert and press Enter
  21. For the Last Name, type Crawford and press Enter
  22. For the Miles Driven, type 396 and press Enter
  23. For the Piecework Rate, type 0.58 and press Enter:
    ===========================================================
     - Piece Work Delivery -
    ===========================================================
    You must provide the information about the truck
    Make:              Chevrolet
    Model:             3500 Express 4x2
    -----------------------------------------------------------
    You must provide the information about the truck driver
    First Name:        Robert
    Last Name:         Crawford
    -----------------------------------------------------------
    Enter the values for the delivery
    Miles Driven:      396
    Piecework Rate:    0.58
    ===========================================================
     - Piece Work Delivery -
    ===========================================================
    Driver:            Robert Crawford
    Truck Details:     Chevrolet 3500 Express 4x2
    -----------------------------------------------------------
    Miles Driven:      396
    Piecework Rate:    0.58
    Gross Salary:      229.68
    ===========================================================
    Press any key to continue . . .
  24. Close the window and return to your programming environment

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 a namespace. Here is an example:

namespace Business
{
    class House
    {
    }
}

Practical LearningPractical Learning: Creating a Namespace

  1. Click the Truck.cs tab to access its class
  2. To create a namespace, change the document as follows:
    namespace BusinessInventory
    {
        /* Piecework is the type of work that is paid on the number 
         * of items produced, the distance driven, etc.
         * In this exercise, a business uses trucks driven by some 
         * employees or contractors to deliver some products. 
         * The drivers are paid based on the distance they travel to 
         * deliver one or many products. */
        public class Truck
        {
            public string make;
            public string model;
        }
    }
  3. Click the Driver.cs tab to access its class and change its document as follows:
    namespace HumanResources
    {
        public class Driver
        {
            public string first_name;
            public string last_name;
        }
    }
  4. Click the PieceDelivery.cs tab to access the file

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 member 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 propNumber;
        public double marketValue;
    }
}

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

        property.propNumber = "D294FF";
        property.marketValue = 425_880;
    }
}

Practical LearningPractical Learning: Accessing a Member of a Namespace

  1. Change the PieceDelivery.cs document as follows:
    using static System.Console;
    
    int miles;
    double pieceworkRate;
    
    WriteLine("===========================================================");
    WriteLine(" - Piece Work Delivery -");
    WriteLine("===========================================================");
    
    BusinessInventory.Truck trk = new BusinessInventory.Truck();
    
    WriteLine("You must provide the information about the truck");
    Write("Make:              ");
    trk.make = ReadLine();
    Write("Model:             ");
    trk.model = ReadLine();
    WriteLine("-----------------------------------------------------------");
    
    HumanResources.Driver drv = new HumanResources.Driver();
    
    WriteLine("You must provide the information about the truck driver");
    Write("First Name:        ");
    drv.first_name = ReadLine();
    Write("Last Name:         ");
    drv.last_name = ReadLine();
    WriteLine("-----------------------------------------------------------");
    
    WriteLine("Enter the values for the delivery");
    Write("Miles Driven:      ");
    miles = int.Parse(ReadLine());
    Write("Piecework Rate:    ");
    pieceworkRate = double.Parse(ReadLine());
    
    WriteLine("===========================================================");
    WriteLine(" - Piece Work Delivery -");
    WriteLine("===========================================================");
    WriteLine("Driver:            " + drv.first_name + " " + drv.last_name);
    WriteLine("Truck Details:     " + trk.make + " " + trk.model);
    WriteLine("-----------------------------------------------------------");
    WriteLine("Miles Driven:      {0}", miles);
    WriteLine("Piecework Rate:    {0}", pieceworkRate);
    WriteLine("Gross Salary:      {0}", miles * pieceworkRate);
    WriteLine("===========================================================");
  2. To execute the project to make sure it is working, on the main menu of Microsoft Visual Studio, click Debug -> Start Without Debugging
  3. When requested, type the Make as Ram and press Enter
  4. For the Model, type 5500 Regular Cab DRW 4x4, Duramag Dry Freight and press Enter
  5. For the First Name, type Joseph and press Enter
  6. For the Last Name, type Garrett and press Enter
  7. For the Miles Driven, type 672 and press Enter
  8. For the Piecework Rate, type 0.36 and press Enter:
    ===========================================================
     - Piece Work Delivery -
    ===========================================================
    You must provide the information about the truck
    Make:              Ram
    Model:             5500 Regular Cab DRW 4x4, Duramag Dry Freight
    -----------------------------------------------------------
    You must provide the information about the truck driver
    First Name:        Joseph
    Last Name:         Garrett
    -----------------------------------------------------------
    Enter the values for the delivery
    Miles Driven:      672
    Piecework Rate:    0.36
    ===========================================================
     - Piece Work Delivery -
    ===========================================================
    Driver:            Joseph Garrett
    Truck Details:     Ram 5500 Regular Cab DRW 4x4, Duramag Dry Freight
    -----------------------------------------------------------
    Miles Driven:      672
    Piecework Rate:    0.36
    Gross Salary:      241.92
    ===========================================================
    Press any key to continue . . .
  9. Close the window and return to your programming environment
Author Note

New Convention:

From now on, in our lessons, when we write namespace-name.layout-name, we mean the layout-name, such as a class, that was created in, or is a member of, the indicated namespace-name.

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:

Using a Namespace

We saw that, to access a class that is a member of a namespace, you must "qualify" the class 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 a keyword named using. 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 PieceDelivery.cs as follows:
    using static System.Console;
    
    // Accessing a namespace
    using HumanResources;
    // Accessing another namespace;
    using BusinessInventory;
    
    int miles;
    double pieceworkRate;
    
    WriteLine("===========================================================");
    WriteLine(" - Piece Work Delivery -");
    WriteLine("===========================================================");
    
    Truck trk = new Truck();
    
    WriteLine("You must provide the information about the truck");
    Write("Make:              ");
    trk.make = ReadLine();
    Write("Model:             ");
    trk.model = ReadLine();
    WriteLine("-----------------------------------------------------------");
    
    Driver drv = new Driver();
    
    WriteLine("You must provide the information about the truck driver");
    Write("First Name:        ");
    drv.first_name = ReadLine();
    Write("Last Name:         ");
    drv.last_name = ReadLine();
    WriteLine("-----------------------------------------------------------");
    
    WriteLine("Enter the values for the delivery");
    Write("Miles Driven:      ");
    miles = int.Parse(ReadLine());
    Write("Piecework Rate:    ");
    pieceworkRate = double.Parse(ReadLine());
    
    WriteLine("===========================================================");
    WriteLine(" - Piece Work Delivery -");
    WriteLine("===========================================================");
    WriteLine("Driver:            " + drv.first_name + " " + drv.last_name);
    WriteLine("Truck Details:     " + trk.make + " " + trk.model);
    WriteLine("-----------------------------------------------------------");
    WriteLine("Miles Driven:      {0}", miles);
    WriteLine("Piecework Rate:    {0}", pieceworkRate);
    WriteLine("Gross Salary:      {0}", miles * pieceworkRate);
    WriteLine("===========================================================");
  2. To execute the project to make sure no error was introduced, on the main menu of Microsoft Visual Studio, click Debug -> Start Without Debugging
  3. When requested, type the Make as Ford and press Enter
  4. For the Model, type E-350 4x2 Rockport Cutaway Van and press Enter
  5. For the First Name, type Jennifer and press Enter
  6. For the Last Name, type Foster and press Enter
  7. For the Miles Driven, type 409 and press Enter
  8. For the Piecework Rate, type 0.48 and press Enter:
    ===========================================================
     - Piece Work Delivery -
    ===========================================================
    You must provide the information about the truck
    Make:              Ford
    Model:             E-350 4x2 Rockport Cutaway Van
    -----------------------------------------------------------
    You must provide the information about the truck driver
    First Name:        Jennifer
    Last Name:         Foster
    -----------------------------------------------------------
    Enter the values for the delivery
    Miles Driven:      409
    Piecework Rate:    0.48
    ===========================================================
     - Piece Work Delivery -
    ===========================================================
    Driver:            Jennifer Foster
    Truck Details:     Ford E-350 4x2 Rockport Cutaway Van
    -----------------------------------------------------------
    Miles Driven:      409
    Piecework Rate:    0.48
    Gross Salary:      196.32
    ===========================================================
    Press any key to continue . . .
  9. Close the window and return to your programming environment
  10. To create a new file, on the main menu, click Project -> Add New Item...
  11. In the middle list, make sure Code File is selected
  12. Change the Name to Contractor
  13. Click Add
  14. In the empty document, type the following:
    namespace SeasonalWork
    {
        public class Contractor
        {
            public string code;
        	public string first_name;
        	public string last_name;
    	public double payRate;
        }
    
        public class TimeRecording
        {
            public string start;
            public string end;
        }
    }
  15. To create a new file, on the main menu, click Project -> Add New Item...
  16. In the middle list, make sure Code File is selected
  17. Change the Name to Agent
  18. Click Add
  19. In the empty document, type the following:
    namespace Marketing
    {
        public class Agent
        {
            public string full_name;
            public string description;
        }
    }
  20. Click the PieceDelivery.cs tab to access the main document of the project
  21. Change the document as follows:
    using static System.Console;
    using Marketing;
    using HumanResources;
    using SeasonalWork;
    using BusinessInventory;
    
    int miles;
    double pieceworkRate;
    
    WriteLine("===========================================================");
    WriteLine(" - Piece Work Delivery -");
    WriteLine("===========================================================");
    
    Truck trk = new Truck();
    
    WriteLine("You must provide the information about the truck");
    Write("Make:              ");
    trk.make = ReadLine();
    Write("Model:             ");
    trk.model = ReadLine();
    WriteLine("-----------------------------------------------------------");
    
    Driver drv = new Driver();
    
    WriteLine("You must provide the information about the truck driver");
    Write("First Name:        ");
    drv.first_name = ReadLine();
    Write("Last Name:         ");
    drv.last_name = ReadLine();
    WriteLine("-----------------------------------------------------------");
    
    WriteLine("Enter the values for the delivery");
    Write("Miles Driven:      ");
    miles = int.Parse(ReadLine());
    Write("Piecework Rate:    ");
    pieceworkRate = double.Parse(ReadLine());
    
    WriteLine("===========================================================");
    WriteLine(" - Piece Work Delivery -");
    WriteLine("===========================================================");
    WriteLine("Driver:            " + drv.first_name + " " + drv.last_name);
    WriteLine("Truck Details:     " + trk.make + " " + trk.model);
    WriteLine("-----------------------------------------------------------");
    WriteLine("Miles Driven:      {0}", miles);
    WriteLine("Piecework Rate:    {0}", pieceworkRate);
    WriteLine("Gross Salary:      {0}", miles * pieceworkRate);
    WriteLine("===========================================================");
  22. To execute the project to make sure it is working, on the main menu of Microsoft Visual Studio, click Debug -> Start Without Debugging
  23. When requested, type the Make as Chevrolet and press Enter
  24. For the Model, type Silverado Medium Duty Regular Cab DRW 4x2, 20' Dry Freight Box and press Enter
  25. For the First Name, type Armin and press Enter
  26. For the Last Name, type Blatz and press Enter
  27. For the Miles Driven, type 771 and press Enter
  28. For the Piecework Rate, type 0.44 and press Enter:
    ===========================================================
     - Piece Work Delivery -
    ===========================================================
    You must provide the information about the truck
    Make:              Chevrolet
    Model:             Silverado Medium Duty Regular Cab DRW 4x2, 20' Dry Freight Box
    -----------------------------------------------------------
    You must provide the information about the truck driver
    First Name:        Armin
    Last Name:         Blatz
    -----------------------------------------------------------
    Enter the values for the delivery
    Miles Driven:      771
    Piecework Rate:    0.44
    ===========================================================
     - Piece Work Delivery -
    ===========================================================
    Driver:            Armin Blatz
    Truck Details:     Chevrolet Silverado Medium Duty Regular Cab DRW 4x2, 20' Dry Freight Box
    -----------------------------------------------------------
    Miles Driven:      771
    Piecework Rate:    0.44
    Gross Salary:      339.24
    ===========================================================
    Press any key to continue . . .

Removing a Namespace

As mentioned above, in the top section of a document, you can create a list of namespaces you are interested to use. Here is an example:

using Accounting;
using HumanResources;
using ResearchAndDevelopment;

public class Exercise
{
}

After making the list of the desired namespaces, you can access their members in your code. Sometimes, you will have added some namespace but not access their members. When that happens, you can remove those namespaces from the top list in the document. You can do that manually. As an alternative, you can right-click anywhere inside the document and click Remove and Sort Usings.

Practical LearningPractical Learning: Removing Namespaces

  1. Right-click anywhere in the PieceDelivery.cs document and click Remove and Sort Usings
  2. To save the document, on the main menu, click File and click Save PieceDelivery.cs

A Namespace from Microsoft Visual Studio

A Namespace from a Project

Microsoft Visual Studio provides different templates you can use to create various types of projects. Except for the empty projects, when you create a non-empty project, the studio creates a file and creates a namespace in that file. That namespace holds the name of the project. The studio also creates a default class in that namespace.

Practical LearningPractical Learning: Creating a Project

  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, make sure C# is selected in the Languages combo box
  3. In the list of project templates, click Console App
  4. Click Next
  5. Change the name to Exercise2
  6. Click Next
  7. In the Framework combo box, make sure .NET 8.0 (Long-Term Support) is selected.
    Click Create

A Namespace from a Class

In Microsoft Visual Studio, to create a new class:

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: Adding a Class to a Project

  1. To create a new class, in the Solution Explorer, right-click the second Exercise2 -> Add -> Class...
  2. In the middle list of the Add New Item dialog box, make sure Class is selected.
  3. Change the file Name to Employee
  4. Click Add.
    Notice that the new class is automatically created in a namespace that holds the name of the project
  5. To execute the project to test, press Ctrl + F5
  6. Press Enter to close the window and return to your programming environment
  7. To start a new project, on the main menu of Microsoft Visual Studio, click File -> New -> Project...
  8. In the list of project templates, click Console App
  9. Click Next
  10. Change the name to QuatroGas1
  11. Click Next
  12. In the Framework combo box, make sure .NET 8.0 (Long-Term Support) is selected.
    Click Create

Creating and Using Many Namespaces

Introduction

In the previous sections, we learned to create one namespace in each document. 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 propNumber;
        public double marketValue;
    }
}

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.

Introduction to Nesting a Namespace

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

namespace Business
{
    class House
    {
        public string propNumber;
        public double marketValue;
    }

    namespace Dealership
    {
    }
}

In the example above, the Dealership namespace is nested inside the Business namespace. After creating the desired namespaces, nested or not, you can create the desired class(es) inside 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 propNumber;
        public double marketValue;
    }

    namespace Dealership
    {
        class Car
        {
            public double marketValue;
        }
    }
}

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

        property.propNumber = "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 other namespaces as you judge necessary.

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

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 one. Here are examples:

namespace Geometry.Quadrilaterals
{
    
}

namespace Geometry.Rounds
{
    
}

In the same way, you can create as many namespaces as necessary inside 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;
    }
}

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

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

A Models Namespace

When working on a project that uses one or more classes, a good way to manage those classes is to create each class in its own file. Instead of creating those classes in the root of the project, it is a good idea to put those classes in a common folder. By tradition, that folder is named Models. In most cases, that is, in most types of projects (except in an ASP.NET MVC application), if you decide to use such a folder, you must manually create it yourself. You can then add a class in that folder. When you do that, the class is created in a namespace that holds the name of the project, a period, and Models.

Practical LearningPractical Learning: Creating a Folder

  1. To create a new folder, in the Solution Explorer, right-click QuatroGas1 -> Add -> New Folder
  2. Type Models as the name of the new folder
  3. To create a new class, in the Solution Explorer, right-click Models -> Add -> Class...
  4. In the middle list of the Add New Item dialog box, make sure Class is selected.
    Change the file Name to GasMeter
  5. Click Add
  6. Right-click anywhere in the document and click Remove and Sort Usings
  7. Change the class as follows:
    namespace QuatroGas2.Models
    {
        internal class GasMeter
        {
            public string MeterNumber { get; set; }
            public string Make        { get; set; }
            public string Model       { get; set; }
        }
    }
  8. To create a new class, in the Solution Explorer, right-click Models -> Add -> Class...
  9. Change the file Name to Customer
  10. Click Add
  11. Change the class as follows:
    namespace QuatroGas2.Models
    {
        internal class Customer
        {
            public string AccountNumber { get; set; }
            public GasMeter GasMeter    { get; set; }
            public string AccountName   { get; set; }
            public string Address       { get; set; }
            public string City          { get; set; }
            public string County        { get; set; }
            public string State         { get; set; }
        }
    }
  12. Access the Program.cs tab and change its documentas follows:
    using QuatroGas1.Models;
    
    GasMeter gs = new GasMeter();
    
    gs.meterId = 100_001;
    
    Console.WriteLine("Quatro Gas");
    Console.WriteLine("=====================");
    Console.WriteLine("Gas Meters");
    Console.WriteLine("---------------------");
    Console.WriteLine("Gas Meter Id: {0}", gs.meterId);
    Console.WriteLine("=====================");
  13. To execute, on the main menu, click Debug -> Start Without Debugging:
    Quatro Gas
    =====================
    Gas Meters
    ---------------------
    Gas Meter Id: 100001
    =====================
    
    Press any key to close this window . . .
  14. Press Enter to close the window and return to your programming environment

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

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.

Here is an example:

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

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 previous 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   ;
        public double marketValue;
    }
}

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

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2024, FunctionX Saturday 29 April 2023 Next