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.

ApplicationPractical Learning: Introducing Namespaces

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New -> Project...
  3. In the middle list, click ASP.NET Web Application (.NET Framework) and se the Name to PayrollPreparation03
  4. Click OK
  5. In the New ASP.NET Web Application, click Empty and press Enter
  6. In the Solution Explorer, right-click PayrollPreparation03 -> Add -> New Folder
  7. Type Content and press Enter
  8. In the Solution Explorer, right-click Content -> Add -> New Item...
  9. In the left frame of the Add New Item dialog box, click Style Sheet
  10. Change the file Name to Site
  11. Press Enter
  12. Create some styles as follows:
    body {
        margin: 0;
        background-color: #ffffff;
    }
    
    h1 { font-size: 1.58em; }
    h2 { font-size: 1.28em; }
    
    .container {
        margin: auto;
        width: 375px;
    }
    
    table      { width: 100%;        }
    .emphasize { font-weight: bold;  }
    .left-col  { width: 120px;       }
    h1, h2, h3 { text-align: center; }
  13. In the Solution Explorer, right-click PayrollPreparation03 -> Add -> New Item...
  14. In the left frame, click Code
  15. In the middle list, click Code File
  16. Change the name to TimeSheet
  17. Press Enter
  18. Create the class as follows:
    public class TimeSheet
    {
        private decimal mon;
        private decimal tue;
        private decimal wed;
        private decimal thu;
        private decimal fri;
    
        public decimal Monday    { set { mon = value; } }
        public decimal Tuesday   { set { tue = value; } }
        public decimal Wednesday { set { wed = value; } }
        public decimal Thursday  { set { thu = value; } }
        public decimal Friday    { set { fri = value; } }
    
        public decimal TimeWorked => mon + tue + wed + thu + fri;
    }
  19. In the Solution Explorer, right-click PayrollPreparation03 -> Add -> New Item...
  20. In the left frame, expand Web and click Razor
  21. In the middle list, click Web Page (Razor v3)
  22. Set the name as Index
  23. Click Add
  24. Change the code as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Fun Department Store - Payroll Preparation</title>
    <link rel="stylesheet" type="text/css" href="~/Content/Site.css" />
    </head>
    <body>
    @{
        TimeSheet ts = new TimeSheet();
        decimal monday = 0M;
        decimal tuesday = 0M;
        decimal wednesday = 0M;
        decimal thursday = 0M;
        decimal friday = 0M;
    
        if (IsPost)
        {
            monday = Request["txtMonday"].AsDecimal();
            tuesday = Request["txtTuesday"].AsDecimal();
            wednesday = Request["txtWednesday"].AsDecimal();
            thursday = Request["txtThursday"].AsDecimal();
            friday = Request["txtFriday"].AsDecimal();
    
            ts.Monday = monday;
            ts.Tuesday = tuesday;
            ts.Wednesday = wednesday;
            ts.Thursday = thursday;
            ts.Friday = friday;
        }
    }
    
    <div class="container">
        <h2>Fun Department Store</h2>
        <h3>- Time Sheet -</h3>
    
        <form name="frmPayroll" method="post">
            <table>
                <tr>
                    <td class="left-col emphasize">Monday:</td>
                    <td><input type="text" name="txtMonday" value="@monday" /></td>
                    <td>&nbsp;</td>
                </tr>
                <tr>
                    <td class="emphasize">Tuesday:</td>
                    <td><input type="text" name="txtTuesday" value="@tuesday" /></td>
                    <td>&nbsp;</td>
                </tr>
                <tr>
                    <td class="emphasize">Wednesday:</td>
                    <td><input type="text" name="txtWednesday" value="@wednesday" /></td>
                    <td>&nbsp;</td>
                </tr>
                <tr>
                    <td class="emphasize">Thursday:</td>
                    <td><input type="text" name="txtThursday" value="@thursday" /></td>
                    <td>&nbsp;</td>
                </tr>
                <tr>
                    <td class="emphasize">Friday:</td>
                    <td><input type="text" name="txtFriday" value="@friday" /></td>
                    <td><input type="submit" name="txtSubmit" value=Calculate /></td>
                </tr>
                <tr>
                    <td class="emphasize">Time Worked:</td>
                    <td><input type="text" name="txtTimeWorked" value="@ts.TimeWorked" /></td>
                    <td>&nbsp;</td>
                </tr>
            </table>
        </form>
    </div>
    </body>
    </html>
  25. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    Introducing Read-Only Properties

  26. Enter some values in the days text boxes, such as 8.00, 10.00, 8.50, 8.00, and 9.00

    Introducing Read-Only Properties

  27. Click the Calculate button

    Introducing Read-Only Properties

  28. Close the browser and return to your programming environment

Manually Creating a Namespace

To create a namespace, type the namespace keyword followed by a name. Like a class, a namespace has a body delimited by curly brackets "{" and "}". Here is an example of creating a namespace:

namespace Metrics
{
}

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

namespace Metrics
{
    public class Conversion
    {
        public decimal InchToCentimeter(decimal number)
        {
            return number * 2.54M;
        }

        public decimal CentimeterToInch(decimal number)
        {
            return number * 0.393701M;
        }
    }
}

ApplicationPractical Learning: Manually Creating a Namespace

  1. Access the TimeSheet.cs file and change the document as follows:
    namespace Accounting
    {
        public class TimeSheet
        {
            private decimal mon;
            private decimal tue;
            private decimal wed;
            private decimal thu;
            private decimal fri;
    
            public decimal Monday { set { mon = value; } }
            public decimal Tuesday { set { tue = value; } }
    
            public decimal Wednesday
            {
                set { wed = value; }
            }
            public decimal Thursday { set { thu = value; } }
            public decimal Friday { set { fri = value; } }
    
            public decimal TimeWorked
            {
                get
                {
                    return mon + tue + wed + thu + fri;
                }
            }
        }
    }
  2. On the Standard toolbar, click the Save button Save

A Namespace from Microsoft Visual Studio

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.

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.

ApplicationPractical Learning: Introducing Automatic Properties

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the middle list, click ASP.NET Web Application (.NET Framework) and set the project Name to Chemistry03
  3. Click OK
  4. In the New ASP.NET Web Application, click Empty and press Enter
  5. In the Solution Explorer, right-click Chemistry03 -> Add -> New Folder
  6. Type Content and press Enter
  7. In the Solution Explorer, right-click Content -> Add -> New Item...
  8. In the left frame of the Add New Item dialog box, click Style Sheet
  9. Change the file Name to Site
  10. Press Enter
  11. Create some styles as follows:
    body {
        margin: 0;
        background-color: white;
    }
    
    h2 { text-align: center; }
    .container {
        width: 300px;
        margin: auto;
    }
    
    .left-col { width:       120px }
    .accent   { font-weight: 600   }
  12. In the Solution Explorer, right-click Chemistry03 - > Add -> Class...
  13. In the middle list, make sure Class is selected.
    Change the name to Element
  14. Click Add
  15. Change the code as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace Chemistry03
    {
        public class Element
        {
            public string   Symbol       { get; set; } = "H";
            public string   ElementName  { get; set; } = "Hydrogen";
            public int      AtomicNumber { get; set; } = 1;
            public decimal  AtomicWeight { get; set; } = 1.009m;
        }
    }
  16. In the Solution Explorer, right-click Chemistry03 -> Add -> New Item...
  17. In the left frame, expand Web and click Razor
  18. In the middle list, click Web Page (Razor v3)
  19. Change the name to Index
  20. Click Add
  21. Change the HTML code as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Chemistry</title>
    <link rel="stylesheet" type="text/css" href="~/Content/Site.css" />
    </head>
    <body>
    <div class="container">
        @{
        }
    
        <h2>Chemistry</h2>
    
        <form name="frmChemistry" method="post">
                <table>
                    <tr>
                        <td class="left-col accent">Symbol:</td>
                        <td><input type="text" name="txtSymbol" value="" /></td>
                    </tr>
                    <tr>
                        <td class="accent">Element Name:</td>
                        <td><input type="text" name="txtElementName" value="" /></td>
                    </tr>
                    <tr>
                        <td class="accent">Atomic Number:</td>
                        <td><input type="text" name="txtAtomicNumber" value="" /></td>
                    </tr>
                    <tr>
                        <td class="accent">Atomic Weight:</td>
                        <td><input type="text" name="txtAtomicWeight" value="" /></td>
                    </tr>
                </table>
        </form>
    </div>
    </body>
    </html>

Accessing the Members of a Namespace

After creating the necessary members of a namespace, you can use the period operator to access an item 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.

ApplicationPractical Learning: Accessing the Content of a Namespace

  1. Change the document as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Chemistry - Neon</title>
    <link rel="stylesheet" type="text/css" href="~/Content/Site.css" />
    </head>
    <body>
    @{
        Chemistry03.Element ne = new Chemistry03.Element();
    
        ne.Symbol = "Ne";
        ne.ElementName = "Neon";
        ne.AtomicNumber = 10;
        ne.AtomicWeight = 20.1797M;
    }
    
    <div class="container">
        <h2>Chemistry - Neon</h2>
    
        <form name="frmChemistry" method="post">
                <table>
                    <tr>
                        <td class="left-col accent">Symbol:</td>
                        <td><input type="text" name="txtSymbol" value="@ne.Symbol" /></td>
                    </tr>
                    <tr>
                        <td class="accent">Element Name:</td>
                        <td><input type="text" name="txtElementName" value="@ne.ElementName" /></td>
                    </tr>
                    <tr>
                        <td class="accent">Atomic Number:</td>
                        <td><input type="text" name="txtAtomicNumber" value="@ne.AtomicNumber" /></td>
                    </tr>
                    <tr>
                        <td class="accent">Atomic Weight:</td>
                        <td><input type="text" name="txtAtomicWeight" value="@ne.AtomicWeight" /></td>
                    </tr>
                </table>
        </form>
    </div>
    </body>
    </html>
  2. Execute the application to test it

    Introduction to Namespaces

  3. Close the browser and return to your programming environment

Creating and Using Many Namespaces

Creating Many Namespaces

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 of a document that contains two namespace: RealEstate and Dealership:

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. This is done by using the name of the namespace, a period, and the name of the class.

ApplicationPractical Learning: Creating Many Namespaces

  1. To open a previous project, on the main menu, click File -> Recent Projects and Solutions -> PayrollPreparation03
  2. Access the TimeSheet.cs file and change its document as follows:
    namespace Accounting
    {
        public class TimeSheet
        {
            private decimal mon;
            private decimal tue;
            private decimal wed;
            private decimal thu;
            private decimal fri;
    
            public decimal Monday { set { mon = value; } }
            public decimal Tuesday { set { tue = value; } }
    
            public decimal Wednesday
            {
                set { wed = value; }
            }
            public decimal Thursday { set { thu = value; } }
            public decimal Friday { set { fri = value; } }
    
            public decimal TimeWorked
            {
                get
                {
                    return mon + tue + wed + thu + fri;
                }
            }
        }
    }
    
    namespace Sales
    {
        public class SoldItem
        {
    
        }
    }
  3. In the Solution Explorer, right-click PayrollPreparation03 -> Add -> New Item...
  4. In the left frame, click Code
  5. In the middle list, click Code File
  6. Change the file Name to Employee
  7. Click Add
  8. In empty document, type the following code:
    namespace HumanResources
    {
        public class Employee
        {
            public string EmployeeNumber { get; set; }
            public string HourlySalary { get; set; }
        }
    }

Using a Namespace

We saw that, to access a class of a namespace, you must "qualify" it using the period operator. Instead of this technique, 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.

ApplicationPractical Learning: Using Namespaces

  1. In the Solution Explorer, right-click PayrollPreparation03 -> Add -> New Item...
  2. In the middle list, make sure Code File is selected.
    Change the file Name to PayrollPreparation
  3. Click Add
  4. In empty document, type the following code:
    using Accounting;
    using HumanResources;
    
    namespace BusinessProcesses
    {
        public class PayrollPreparation
        {
            private Employee staff;
            private TimeSheet ts;
        }
    }

Introduction to 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 of a nested namespace named Dealership:

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
{
    public void Create()
    {
        Business.House property = new Business.House();

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

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

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

ApplicationPractical Learning: Nesting a Namespace

  1. Access the TimeSheet.cs file and change it as follows:
    namespace Accounting
    {
        namespace PayrollProcesses
        {
            public class TimeSheet
            {
                private decimal mon;
                private decimal tue;
                private decimal wed;
                private decimal thu;
                private decimal fri;
    
                public decimal Monday { set { mon = value; } }
                public decimal Tuesday { set { tue = value; } }
    
                public decimal Wednesday
                {
                    set { wed = value; }
                }
                public decimal Thursday { set { thu = value; } }
                public decimal Friday { set { fri = value; } }
    
                public decimal TimeWorked
                {
                    get
                    {
                        return mon + tue + wed + thu + fri;
                    }
                }
            }
        }
    }
  2. Access the PayrollPreparation.cs file and change its document as follows:
    using Accounting.PayrollProcesses;
    using HumanResources;
    
    namespace BusinessProcesses
    {
        public class PayrollPreparation
        {
            private Employee staff;
            private TimeSheet ts;
        }
    }

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

public class Exercise
{
    public void Create()
    {
        Geometry.Quadrilaterals.Square sqr = new Geometry.Quadrilaterals.Square();

        sqr.side = 25.85M;
    }
}

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

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

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

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

ApplicationPractical Learning: Nesting a Namespace by Name

  1. Access the Employee.cs file and change its document as follows:
    namespace HumanResources.PersonnelRecords
    {
        public class Employee
        {
            public string EmployeeNumber { get; set; }
            public string HourlySalary { get; set; }
        }
    }
  2. Access the PayrollPreparation.cs file and change its document as follows:
    using Accounting.PayrollProcesses;
    using HumanResources.PersonnelRecords;
    
    namespace BusinessProcesses.Taxes.CommunityIssues
    {
        public class PayrollPreparation
        {
            private Employee staff;
            private TimeSheet ts;
        }
    }
  3. On the Standard toolbar, click the Save All button Save All

The ASP.NET App_Code Folder

So far, we were creating our classes in the root directory of the project. As you have seen so far, there is nothing wrong with that and the code worked just fine. Still, for a better organization of your project, it is recommended that you put your classes in folders. One of the special folders you can use is named App_Code.

To generate the App_Code folder:

After getting the App_Code folder, you can create a class in it by using the Add -> Class... menu item. In you do that, Microsoft Visual Studio would create a namespace using the name of the project. Then if would nest the App_Code in that folder by name. The new class would be created in that App_code nested namespace.

ApplicationPractical Learning: Introducing the ASP.NET App_Code Folder

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the middle list, click ASP.NET Web Application (.NET Framework) and set the project Name to Chemistry04
  3. Click OK
  4. In the New ASP.NET Web Application, click Empty and press Enter
  5. In the Solution Explorer, right-click Chemistry04 -> Add -> New Folder
  6. Type Content and press Enter
  7. In the Solution Explorer, right-click Content -> Add -> New Item...
  8. In the left frame of the Add New Item dialog box, click Style Sheet
  9. Change the file Name to Site
  10. Press Enter
  11. Create some styles as follows:
    body {
        margin: 0;
        background-color: #FFFFFF;
    }
    
    #top-banner {
        top: 0;
        width: 100%;
        height: 60px;
        position: fixed;
        background-color: #003366;
        border-bottom: 5px solid black;
    }
    
    .title-holder {
        top: 65px;
        width: 100%;
        height: 34px;
        position: fixed;
    }
    
    .container {
        width: 300px;
        margin: auto;
        padding-top: 120px;
    }
    
    #main-title {
        font-weight: 800;
        margin-top: 16px;
        font-size: 2.12em;
        text-align: center;
        color: antiquewhite;
        font-family: Garamond, 'Times New Roman', Georgia, serif
    }
    
    #sub-title {
        color: navy;
        font-weight: 600;
        padding-top: 2px;
        font-size: 1.68em;
        text-align: center;
        font-family: Garamond, 'Times New Roman', Georgia, serif
    }
    
    .emphasize { font-weight: bold; }
    .left-col  { width:      120px; }
  12. In the Solution Explorer, right-click Chemistry04. Position the mouse on Add. Position the mouse on Add ASP.NET Folder. Click App_Code
  13. In the Solution Explorer, right-click App_Code -> Add -> Class...
  14. In the middle list, make sure Class is selected.
    Change the name to Element
  15. Click Add
  16. Change the code as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace Chemistry04.App_Code
    {
        public class Element
        {
            public string   Symbol       { get; set; } = "H";
            public string   ElementName  { get; set; } = "Hydrogen";
            public int      AtomicNumber { get; set; } = 1;
            public decimal  AtomicWeight { get; set; } = 1.008m;
        }
    }
  17. In the Solution Explorer, right-click Chemistry04 -> Add -> New Item...
  18. In the left frame, expand Web and click Razor
  19. In the middle list, click Web Page (Razor v3)
  20. Change the name to Index
  21. Click Add
  22. Change the HTML code as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Chemistry :: </title>
    <link rel="stylesheet" type="text/css" href="~/Content/Site.css" />
    </head>
    <body>
    @{
    
    }
    
    <div id="top-banner">
        <p id="main-title">Chemistry</p>
    </div>
    
    <div class="title-holder">
        <div id="sub-title"></div>
        <hr />
    </div>
        
    <div class="container">
        <form name="frmChemistry" method="post">
            <table>
                <tr>
                    <td class="left-col emphasize">Symbol:</td>
                    <td><input type="text" name="txtSymbol" value="" /></td>
                </tr>
                <tr>
                    <td class="emphasize">Element Name:</td>
                    <td><input type="text" name="txtElementName" value="" /></td>
                </tr>
                <tr>
                    <td class="emphasize">Atomic Number:</td>
                    <td><input type="text" name="txtAtomicNumber" value="" /></td>
                </tr>
                <tr>
                    <td class="emphasize">Atomic Weight:</td>
                    <td><input type="text" name="txtAtomicWeight" value="" /></td>
                </tr>
            </table>
        </form>
    </div>
    </body>
    </html>
  23. To execute the application, on the main menu, click Debug -> Start Without Debugging

    Introduction to Namespaces

  24. Close the browser and return to your programming environment
  25. Change the document as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Chemistry :: Sodium</title>
    <link rel="stylesheet" type="text/css" href="~/Content/Site.css" />
    </head>
    <body>
    @{
        Chemistry04.App_Code.Element na = new Chemistry04.App_Code.Element();
    
        na.Symbol = "Na";
        na.ElementName = "Sodium";
        na.AtomicNumber = 11;
        na.AtomicWeight = 22.98976928M;
    }
    
    <div id="top-banner">
        <p id="main-title">Chemistry</p>
    </div>
    
    <div class="title-holder">
        <div id="sub-title">Sodium</div>
        <hr />
    </div>
        
    <div class="container">
        <form name="frmChemistry" method="post">
            <table>
                <tr>
                    <td class="left-col emphasize">Symbol:</td>
                    <td><input type="text" name="txtSymbol" value="@na.Symbol" /></td>
                </tr>
                <tr>
                    <td class="emphasize">Element Name:</td>
                    <td><input type="text" name="txtElementName" value="@na.ElementName" /></td>
                </tr>
                <tr>
                    <td class="emphasize">Atomic Number:</td>
                    <td><input type="text" name="txtAtomicNumber" value="@na.AtomicNumber" /></td>
                </tr>
                <tr>
                    <td class="emphasize">Atomic Weight:</td>
                    <td><input type="text" name="txtAtomicWeight" value="@na.AtomicWeight" /></td>
                </tr>
            </table>
        </form>
    </div>
    </body>
    </html>
  26. To execute the application, on the main menu, click Debug -> Start Without Debugging

    Introduction to Namespaces

  27. Close the browser and return to your programming environment

Class Overloading?

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. An 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 is to use a feature named generic. A generic class has a name that ends with (something like) <T>. In this case, 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;
    }
}

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 a name (any name you want), followed by =, followed by the complete namespace. After doing this, you can then use the alias in place of the namespace.

Properties and Namespaces

Sometimes you want to create a property that is a type created in a namepace. Consider the following namespaces:

namespace Chemistry
{
    public class Element
    {
    }
}

To create a property that uses a type included in an external namespace, you can qualify its type. Here is an example:

namespace Chemistry
{
    public class Element
    {
    }
}

public class Atom
{
    public Chemistry.Element Element { get; set; }
}

As an aternative, or in most cases, you can include the namespace in the top section of the file using the using keyword. Here is an example:

using Chemistry;

public class Atom
{
    public Element Element { get; set; }
}

The using expression if useful only if there is no possibility of name conflicts in the code. Otherwise, it is safer to qualify the type.

Sometimes you want to create a property that is a type nested in a namepace. Consider the following Proton class created in a namespace named Protons that itself is nested:

namespace Chemistry
{
    public class Element
    {
    }

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

To create a property of a type that belongs to a nested namespace, you can quality its type. Here is an example:

namespace Chemistry
{
    public class Element
    {
    }

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

public class Nucleus
{
    public Chemistry.Atoms.Nucleons.Proton Proton { get; set; }
}

public class Atom
{
    public Chemistry.ChemicalElement Element { get; set; }
    public Nucleus Nucleus { get; set; }
}

Managing Namespaces

Inserting a Namespace

If you have existing code already, you can include it in a namespace. To do that manually, click above the section of code, type namespace followed by a name and {. Locate the end of the section and type }.

If you are using Microsoft Visual Studio, select the code you want to include in a namespace. Right-click the selection, position the mouse on Snippet, and click Surround With... In the list, double-click namespace. A namespace with a default name would be added. You can accept or change the name.

Renaming a Namespace

Renaming a namespace follows the same logic of variables, classes, and methods. If you are using Microsoft Visual Studio, to rename a namespace:

ApplicationPractical Learning: Ending the Lesson


Previous Copyright © 2001-2019, FunctionX Next