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; }
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("===========================================================");
=========================================================== - 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 . . .
Manually Creating 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:
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 Learning: Accessing a Member of a Namespace
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("===========================================================");
=========================================================== - 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 . . .
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:
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 Learning: Using Namespaces
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("===========================================================");
=========================================================== - 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 . . .
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; } }
namespace Marketing { public class Agent { public string full_name; public string description; } }
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("===========================================================");
=========================================================== - 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 Learning: Removing Namespaces
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 Learning: Creating a Project
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 Learning: Adding a Class to a Project
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.
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; } }
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 Learning: Creating a Folder
namespace QuatroGas2.Models
{
internal class GasMeter
{
public string MeterNumber { get; set; }
public string Make { get; set; }
public string Model { get; set; }
}
}
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; }
}
}
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("=====================");
Quatro Gas ===================== Gas Meters --------------------- Gas Meter Id: 100001 ===================== Press any key to close this window . . .
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 Learning: Ending the Lesson
|
|||
Previous | Copyright © 2001-2024, FunctionX | Saturday 29 April 2023 | Next |
|