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, a city, etc.
Practical Learning: Introducing Namespaces
public class Driver { public string first_name; public string last_name; }
/* 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; }
@page @model PieceWork1.Pages.PieceDeliveryModel @{ int miles; double pieceworkRate; Truck trk = new Truck(); Driver drv = new Driver(); drv.first_name = "Robert"; drv.last_name = "Crawford"; trk.make = "Chevrolet "; trk.model = "3500 Express 4x2"; miles = 396; pieceworkRate = 0.58; double pay = miles * pieceworkRate; string strPay = $"{pay:F}"; } <h3 style="text-align: center"> - Piece Work Delivery -</h3> <hr /> <table width="350" align="center"> <tr> <td width="125">Driver:</td> <td>@drv.first_name @drv.last_name</td> </tr> <tr> <td>Truck Details:</td> <td>@trk.make @trk.model</td> </tr> </table> <hr /> <table align="center" width="350"> <tr> <td width="125">Miles Driven:</td> <td>@miles</td> </tr> <tr> <td>Piecework Rate:</td> <td>@pieceworkRate</td> </tr> <tr> <td>Gross Salary:</td> <td>@strPay</td> </tr> </table>
- Piece Work Delivery - Driver: Robert Crawford Truck Details: Chevrolet 3500 Express 4x2 Miles Driven: 396 Piecework Rate: 0.58 Gross Salary: 229.68
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 Learning: Creating a Namespace
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; } }
namespace HumanResources { public class Driver { public string first_name; public string last_name; } }
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:
// This class is created in a Code File namespace Business { class House { public string propNumber; public double marketValue; } } // This section is from a webpage @page @model Valuable.Pages.FoundationsModel @{ Business.House property = new Business.House(); prop.propNumber = "D294FF"; prop.marketValue = 425_880; } <pre>=//= Altair Realtors =//= Properties Inventory Property #: @prop.propNumber Market Value: @prop.marketValue</pre>
This would produce:
=//= Altair Realtors =//= Properties Inventory Property #: D294FF Market Value: 425880
Practical Learning: Accessing a Member of a Namespace
@page @model PieceWork1.Pages.PieceDeliveryModel @{ int miles; double pieceworkRate; BusinessInventory.Truck trk = new BusinessInventory.Truck(); HumanResources.Driver drv = new HumanResources.Driver(); drv.first_name = "Joseph"; drv.last_name = "Garrett"; trk.make = "Ram"; trk.model = "5500 Regular Cab DRW 4x4, Duramag Dry Freight"; miles = 672; pieceworkRate = 0.36; double pay = miles * pieceworkRate; string strPay = $"{pay:F}"; } <h3 style="text-align: center"> - Piece Work Delivery -</h3> <hr /> <table width="350" align="center"> <tr> <td width="125">Driver:</td> <td>@drv.first_name @drv.last_name</td> </tr> <tr> <td>Truck Details:</td> <td>@trk.make @trk.model</td> </tr> </table> <hr /> <table align="center" width="350"> <tr> <td width="125">Miles Driven:</td> <td>@miles</td> </tr> <tr> <td>Piecework Rate:</td> <td>@pieceworkRate</td> </tr> <tr> <td>Gross Salary:</td> <td>@strPay</td> </tr> </table>
- 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
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 in a Code File
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, even if you use the using keyword, you must still qualify the name of the class.
Using a Namespace in a Razor Page
you can reference a namespace in a razor page. The formula is almost the same as when referencing a namespace in a code file. In a razor page, precede the using keyword with the @ symbol and don't end the statement with a semicolon.
Practical Learning: Using Namespaces
@page
@model PieceWork1.Pages.PieceDeliveryModel
@using BusinessInventory
@using HumanResources
@{
int miles;
double pieceworkRate;
Truck trk = new Truck();
Driver drv = new Driver();
drv.first_name = "Jennifer";
drv.last_name = "Foster";
trk.make = "Ford";
trk.model = "E-350 4x2 Rockport Cutaway Van";
miles = 409;
pieceworkRate = 0.48;
double pay = miles * pieceworkRate;
string strPay = $"{pay:F}";
}
<h3 style="text-align: center"> - Piece Work Delivery -</h3>
<hr />
<table width="350" align="center">
<tr>
<td width="125">Driver:</td>
<td>@drv.first_name @drv.last_name</td>
</tr>
<tr>
<td>Truck Details:</td>
<td>@trk.make @trk.model</td>
</tr>
</table>
<hr />
<table align="center" width="350">
<tr>
<td width="125">Miles Driven:</td>
<td>@miles</td>
</tr>
<tr>
<td>Piecework Rate:</td>
<td>@pieceworkRate</td>
</tr>
<tr>
<td>Gross Salary:</td>
<td>@strPay</td>
</tr>
</table>
- 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
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.
Namespaces from a Project
Introduction
If you create an ASP.NET Core Web project in Microsoft Visual Studio, the studio creates some namespaces and adds classes to those namespaces. The studio uses the name of the project for the namespace.
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.
A Models Namespace
When you work in an ASP.NET environment (Core, MVC, etc), it is recommended that you create you classes in a folder named Models. If you create an MVC application in Microsoft Visual Studio, the studio would automatically reate a Models folder for you. If you are creating an ASP.NET Core Web application, that folder is not automatically created for you: You must manually create it.
To manually create a Models folder in an ASP.NET Core Web application, in the Solution Explorer, right-click the name of the project, position the mouse on Add, and click New Folder. Then type Models as the name of the folder. You can then create a class in the Models folder. To do this, in the Solution Explorer, right-click Models, position the mouse on Add, and click Class... Give a name to the class and click Add.
When you create a folder named Models, Microsoft Visual Studio creates a namespace that is a combination of the name of the project, a period, and Models. Whenever you add a class to the Models folder, the class is created and put in the Models namespace. Whenever you need to reference that class, if you are working in a regular code file, in the top section of the file, you can type using followed by the whole namespace. If you are working in a razor page, in the top section of the file, after the @page and the @model... lines, type @using followed by the namespace.
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:
@page @model Valuable.Pages.FoundationsModel @using Business; @{ Business.House property = new Business.House(); property.propNumber = "D294FF"; property.marketValue = 425880; Business.Dealership.Car vehicle = new Business.Dealership.Car(); vehicle.marketValue = 38425.50; } <pre>=//= Altair Realtors =//= Properties Inventory Property #: @prop.propNumber Market Value: @prop.marketValue ============================== Car Leadership Market Value: @vehicle.marketValue</pre>
This would produce:
=//= Altair Realtors =//= Properties Inventory Property #: D294FF Market Value: 425880 ============================== Car Leadership Market Value: 38425.5
In the same way, you can nest as many namespaces inside 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
{
}
you can then add content to that namespace, including creating one or more classes in it. Here is an example that contains a class:
namespace Geometry.Quadrilaterals { class Square { public double side; } }
After creating the nested namespace and filling it with the desired content, you can access its member(s) by qualifying it(them). Here is an example:
@page @model Valuable.Pages.FoundationsModel @{ Geometry.Quadrilaterals.Square sqr = new Geometry.Quadrilaterals.Square(); sqr.side = 25.85; } <pre>=//= Geometry =//= Square Side: @sqr.side</pre>
This would produce:
=//= Geometry =//= Square 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, You can add content to it. Here are examples:
namespace Geometry.Quadrilaterals
{
class Square
{
public double side;
}
}
namespace Geometry.Volumes.Elliptic
{
class Cylinder
{
public double radius;
}
}
As mentioned already, to access the content of a nested namespace, you can qualify the desired name. Here is an example:
@page @model Valuable.Pages.FoundationsModel @{ 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; } <pre>=//= Geometry =//= Square Side: @sqr.side ======================= Cylinder Radius: @cyl.radius</pre>
This would produce:
=//= Geometry =//= Square Side: 25.85 ======================= Cylinder Radius: 36.85
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 { 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;
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 Learning: Ending the Lesson
|
|||
Previous | Copyright © 2001-2023, C# Key | Tuesday 16 November 2021 | Next |
|