Introduction to Namespaces
Introduction to 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.
Practical Learning: Introducing Namespaces
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; }
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; }
<!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> </td> </tr> <tr> <td class="emphasize">Tuesday:</td> <td><input type="text" name="txtTuesday" value="@tuesday" /></td> <td> </td> </tr> <tr> <td class="emphasize">Wednesday:</td> <td><input type="text" name="txtWednesday" value="@wednesday" /></td> <td> </td> </tr> <tr> <td class="emphasize">Thursday:</td> <td><input type="text" name="txtThursday" value="@thursday" /></td> <td> </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> </td> </tr> </table> </form> </div> </body> </html>
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;
}
}
}
Practical Learning: Manually Creating a Namespace
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; } } } }
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.
Practical Learning: Introducing Automatic Properties
body { margin: 0; background-color: white; } h2 { text-align: center; } .container { width: 300px; margin: auto; } .left-col { width: 120px } .accent { font-weight: 600 }
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; } }
<!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.
Practical Learning: Accessing the Content of a Namespace
<!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>
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.
Practical Learning: Creating Many Namespaces
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
{
}
}
namespace HumanResources { public class Employee { public string EmployeeNumber { get; set; } public string HourlySalary { get; set; } } }
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.
Practical Learning: Using Namespaces
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.
Practical Learning: Nesting a Namespace
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; } } } } }
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; } }
Practical Learning: Nesting a Namespace by Name
namespace HumanResources.PersonnelRecords
{
public class Employee
{
public string EmployeeNumber { get; set; }
public string HourlySalary { get; set; }
}
}
using Accounting.PayrollProcesses; using HumanResources.PersonnelRecords; namespace BusinessProcesses.Taxes.CommunityIssues { public class PayrollPreparation { private Employee staff; private TimeSheet ts; } }
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.
Practical Learning: Introducing the ASP.NET App_Code Folder
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; }
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;
}
}
<!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>
<!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>
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:
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2019, FunctionX | Next |
|