Application: Introducing Namespaces
|
|
- Start Microsoft Visual Studio
- To create a new project, on the main menu, click File -> New Project
- In the left list, click Windows
- In the right list, click Empty Project
- Change the name to DepartmentStore4
- Click OK
- To create a new file, on the main menu, click Project -> Add New Item...
- In the left list, click Code
- In the right list, click Code File
- Change the Name to DepartmentStore and press Add
- In the empty document, type the following:
public class DepartmentStore
{
static int Main()
{
return 0;
}
}
Manually Creating a Namespace
|
|
To create a namespace:
- Type code that starts with the namespace keyword followed by the name of the section
- Right-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
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 of a namespace. Here is an example:
namespace Business
{
class House
{
}
}
Application: Creating a Namespace
|
|
An Automatically Generated Namespace
|
|
In Lesson 5, we mentioned that, to create a new class:
- On the main menu, you can click Project -> Add Class...
- In the Solution Explorer, you can right-click the name of the project -> Add -> click Class...
- In the Class View, you can right-click the name of the Project -> Add -> Class...
If you use any of these approaches, Microsoft Visual C# 2010 Express or Microsoft Visual Studio would create a namespace using the name of the project and wouold add the new class to it.
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 part 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
{
public class House
{
public string propertyNumber;
public decimal price;
}
}
public class Exercise
{
static void Main()
{
Business.House property = new Business.House();
property.propertyNumber = "D294FF";
property.Price = 425880;
}
}
Application: Accessing Members of a Namespace
|
|
- To access the content of a namespace, change the document as follows:
public class DepartmentStore
{
static int Main()
{
Store.StoreItem si = new Store.StoreItem();
si.itemNumber = 613508;
si.itemName = "Merino Crew Neck Cardigan";
si.unitPrice = 80.00M;
System.Console.WriteLine("Store Inventory");
System.Console.Write("Item #: ");
System.Console.WriteLine(si.itemNumber);
System.Console.Write("Item Name: ");
System.Console.WriteLine(si.itemName);
System.Console.Write("Unit Price: ");
System.Console.WriteLine(si.unitPrice);
System.Console.ReadKey();
return 0;
}
}
namespace Store
{
public class StoreItem
{
public int itemNumber;
public string itemName;
public decimal unitPrice;
}
}
- Execute the application to see the result:
Store Inventory
Item #: 613508
Item Name: Merino Crew Neck Cardigan
Unit Price: 80.00
- Press Enter and return to your programming environment
Creating and Using 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:
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.
Application: Creating Many Namespaces
|
|
- To create a new file, on the main menu, click Project -> Add New Item...
- If necessary, in the left list, click Code.
In the right list, click Code File
- Change the Name to Records and press Add
- Change the document as follows:
namespace Store
{
public class StoreItem
{
public int itemNumber;
public string itemName;
public decimal unitPrice;
}
}
- To create a new file, on the main menu, click Project -> Add New Item...
- If necessary, in the left list, click Code.
In the right list, click Code File
- Change the Name to Suppliers and press Add
- Change the document as follows:
namespace Supply
{
public class Manufacturer
{
public string companyName;
public string contactName;
public string contactPhone;
}
}
- To access the other file, click the DepartmentStore.cs label
- To use the namespaces, change the document as follows:
public class DepartmentStore
{
static int Main()
{
Supply.Manufacturer dealer = new Supply.Manufacturer();
dealer.companyName = "Peel Corp";
dealer.contactName = "Sylvain Yobo";
dealer.contactPhone = "(602) 791-8074";
Store.StoreItem si = new Store.StoreItem();
si.itemNumber = 613508;
si.itemName = "Merino Crew Neck Cardigan";
si.unitPrice = 80.00M;
System.Console.WriteLine("Store Inventory");
System.Console.Write("Item #: ");
System.Console.WriteLine(si.itemNumber);
System.Console.Write("Item Name: ");
System.Console.WriteLine(si.itemName);
System.Console.Write("Unit Price: ");
System.Console.WriteLine(si.unitPrice);
System.Console.ReadKey();
return 0;
}
}
We saw that, to call an object or a method that is part of a namespace, you must "qualify" the object using the period operator. Instead of using this approach, 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. In fact, when there is 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 using, you must still qualify the name of the class.
Application: Using Namespaces
|
|
- To use the using keyword, change the document as follows:
using Supply;
using Store;
public class DepartmentStore
{
static int Main()
{
Manufacturer dealer = new 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.00M;
System.Console.WriteLine("Manufacturer Information");
System.Console.Write("Company Name: ");
System.Console.WriteLine(dealer.companyName);
System.Console.Write("Contact Name: ");
System.Console.WriteLine(dealer.contactName);
System.Console.Write("Contact Phone: ");
System.Console.WriteLine(dealer.contactPhone);
System.Console.WriteLine("---------------------------------------");
System.Console.WriteLine("Store Inventory");
System.Console.Write("Item #: ");
System.Console.WriteLine(si.itemNumber);
System.Console.Write("Item Name: ");
System.Console.WriteLine(si.itemName);
System.Console.Write("Unit Price: ");
System.Console.WriteLine(si.unitPrice);
System.Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
System.Console.ReadKey();
return 0;
}
}
- Execute the application to see the result:
Manufacturer Information
Company Name: Peel Corp
Contact Name: Sylvain Yobo
Contact Phone: (602) 791-8074
---------------------------------------
Store Inventory
Item #: 613508
Item Name: Merino Crew Neck Cardigan
Unit Price: 80.00
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- Press Enter and return to your programming environment
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:
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
{
static void Main()
{
Business.House property = new Business.House();
property.propertyNumber = "D294FF";
property.price = 425880;
Business.Dealership.Car vehicle = new Business.Dealership.Car();
vehicle.price = 38425.50M;
}
}
In the same way, you can nest as many namespaces inside of 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
{
public class Square
{
public double side;
}
}
public class Exercise
{
public 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 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 double side;
}
}
namespace Geometry.Volumes.Elliptic
{
public class Cylinder
{
public double radius;
}
}
public class Exercise
{
public 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;
}
}
Application: Nesting Namespaces
|
|
- Click the Records.cs label to access its document and change it as follows:
namespace Store
{
namespace Inventory
{
public class StoreItem
{
public int itemNumber;
public string itemName;
public decimal unitPrice;
}
}
namespace Personel
{
namespace PayrollRecords
{
public class Employee
{
public string firstName;
public string lastName;
public decimal HourlySalary;
}
public class Contractors
{
public string FullName;
public int ContractStatus;
}
}
}
}
- Access the DepartmentStore.cs file and change it as follows:
using Supply;
using Store.Inventory;
public class DepartmentStore
{
static int Main()
{
. . . No Change
return 0;
}
}
Class Overloading? No Way! Way
|
|
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. One 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 will be available when we study generics. That is, in the same namespace, one of the classes can be a generic and the other not. Here is an example:
namespace Arithmetic
{
public class Numbers
{
public int value;
}
public class Numbers<T>
{
public int value;
}
}
Application: Using a Commonly Named Class
|
|
- Access the Suppliers.cs file and change it as follows:
namespace Supply
{
public class SalesPerson
{
public string fullName;
public string expertise;
public string phoneNumber;
}
}
namespace Manufacturers.Domestic
{
public class Manufacturer
{
public string companyName;
public string contactName;
public string contactPhone;
}
}
namespace Manufacturers.Foreign.Asia
{
public class Manufacturer
{
public string country;
public string companyName;
public string contactName;
public string contactPhone;
public string webSite;
}
}
- Access the DepartmentStore.cs file and change it as follows:
using Supply;
using Manufacturers.Foreign.Asia;
using Store.Inventory;
public class DepartmentStore
{
static int Main()
{
. . . No Change
return 0;
}
}
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.
Application: Creating and Using an Alias
|
|
- Access the DepartmentStore.cs file and change it as follows:
using Supply;
using Asian = Manufacturers.Foreign.Asia;
using Store.Inventory;
public class DepartmentStore
{
static int 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.00M;
System.Console.WriteLine("Manufacturer Information");
System.Console.Write("Company Name: ");
System.Console.WriteLine(dealer.companyName);
System.Console.Write("Contact Name: ");
System.Console.WriteLine(dealer.contactName);
System.Console.Write("Contact Phone: ");
System.Console.WriteLine(dealer.contactPhone);
System.Console.WriteLine("---------------------------------------");
System.Console.WriteLine("Store Inventory");
System.Console.Write("Item #: ");
System.Console.WriteLine(si.itemNumber);
System.Console.Write("Item Name: ");
System.Console.WriteLine(si.itemName);
System.Console.Write("Unit Price: ");
System.Console.WriteLine(si.unitPrice);
System.Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
System.Console.ReadKey();
return 0;
}
}
- Execute the application to see the result
- Close the DOS window and return to your programming environment
If you have existing code already, you can include it in a namespace. To do that:
- Click above the section of code, type namespace followed by a name and {. Locate the end of the section and type }
- Select the code that you want to include in a namespace. Right-click the selection and click Surround With... In the list, double-click namespace
Renaming a namespace follows the same logic we reviewed for variables, classes, and methods: you can manually rename it or benefit from the assistance of the Code Editor. To rename a namespace:
- In the Code Editor, locate its name and change it. Then click the arrow of its tag and choose an option from the menu
- Right-click the name and click Rename... Then follow the dialog boxes as we have reviewed already
Namespaces and Inheritance
|
|
Imagine you had created a class named Person in a namespace named People as follows:
using System;
namespace People
{
public class Person
{
private string _name;
private string _gdr;
public Person(string name = "Not Available",
string gender = "Unknown")
{
this._name = name;
this._gdr = gender;
}
private string FullName
{
get { return _name; }
set { _name = value; }
}
private string Gender
{
get { return _gdr; }
set { _gdr = value; }
}
}
}
If you decide to derive a class from it, remember that this class belongs to a namespace. To inherit from this class, the compiler will need to know the namespace in which the class was created. Class inheritance that involves namespaces relies on qualification, like the calling of the members of a namespace. To derive a class from a class member of a namespace, type the name of the namespace, followed by the period operator ".", and followed by the name of the base namespace. Here is an example:
Source File: StaffMembers.cs |
using System;
namespace HighSchool
{
public class Teacher : People.Person
{
private string _pos;
public Teacher(string pos = "Staff Member")
{
this._pos = pos;
}
private string Position
{
get { return _pos; }
set { _pos = value; }
}
}
}
|
If you need to call the class that was defined in a different namespace, remember to qualify its name with the period operator. Here is an example:
Source File: Exercise.cs |
using System;
class Exercise
{
public static int Main()
{
People.Person man = new People.Person("Herman Sandt", "Male");
HighSchool.Teacher staff = new HighSchool.Teacher("Vice Principal");
Console.WriteLine();
return 0;
}
}
|
Alternatively, to use the contents of a namespace, prior to calling a member of that namespace, you can type the using keyword followed by the name of the namespace. Here is an example:
Source File: Exercise.cs |
using System;
using People;
using HighSchool;
class Exercise
{
public static int Main()
{
Person man = new Person("Herman Sandt", "Male");
Teacher staff = new Teacher("Vice Principal");
Console.WriteLine();
return 0;
}
}
|
Application: Using Inheritance With Namespaces
|
|
- To create a new application, on the main menu, click File -> New Project...
- In the middle list, click Empty Project
- Set the Name to Geometry3 and press Enter
- To create a new class, on the main menu, click Project -> Add Class...
- Set the Name to Square and press Enter
- Change the file as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry3
{
public class Square
{
private double sd;
public Square(double s = 0.00D)
{
this.sd = s;
}
}
}
- To create a new class, on the main menu, click Project -> Add Class...
- Set the Name to Rectangle and press Enter
- Change the file as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry3
{
public class Rectangle
{
double len;
double hgt;
public Rectangle(double L = 0.00D, double H = 0.00D)
{
this.len = L;
this.hgt = H;
}
}
}
Introduction to Built-In Namespaces
|
|
The .NET Framework is a very rich, powerful, and expanded library. Its primary power is in its large set of classes. To organize these classes, the .NET Framework provides many namespaces. Each namespace is used to provide a specific set of classes.
To help you examine the namespaces of the .NET Framework, Microsoft Visual Studio (not Microsoft Visual C# 2010 Express) provides the Object Browser. To access it
- On the main menu, click View -> Object Browser
- On the Standard toolbar, click the Object Browser button
- Press F2
The Object is made of three frames:
The left frame shows a list of libraries. Notice that some nodes show a series of numbers between square brackets. This represents the version of the .NET Framework. When different nodes with the same name have square brackets, it means the library has been created or updated in different versions. For example, 4.0.0.0 represents Microsoft .NET Framework 4.0
Because most libraries contain more than one namespace, each node is equipped with a + button. To expand a node, click the + button. After expanding a library, the namespaces it contain appear as nodes. Because most namespaces contain more than one class, each namespace is equipped with a + button. To expand it, you can click the + button. After expanding a namespace, its list of classes appear. To show the members of a class, in the left frame, click it:
To get an explanation or description of a member of the class, in the top-right frame, click that member. The bottom-right frame presents some information about the selected item.
Introduction to the System Namespace
|
|
The most regularly used namespace in the .NET Framework is called System. So far, to use the Systemnamespace, we typed it inside a method. Here is an example:
public class Exercise
{
static int Main()
{
System.Console.WriteLine("The wonderful world of C# programming");
return 0;
}
}
You can also precede System with global and the :: operator. Here is an example:
public class Exercise
{
static int Main()
{
global::System.Console.WriteLine("The wonderful world of C# programming");
return 0;
}
}
We learned that, to access a namespace, you can use the using keyword. In the same way, you can use using to refer to the System namespace. Here is an example:
using System;
public class Exercise
{
static int Main()
{
System.Console.WriteLine("The wonderful world of C# programming");
return 0;
}
}
This time too, you can precede System with global::
using global::System;
public class Exercise
{
static int Main()
{
System.Console.WriteLine("The wonderful world of C# programming");
return 0;
}
}
Once you have used using System or using global::System, you can use or omit System in the body of the function. Here is an example:
using System;
public class Exercise
{
static int Main()
{
Console.WriteLine("The wonderful world of C# programming");
return 0;
}
}
Introduction to Other Namespaces
|
|
The .NET Framework provides an incredibly long list of namespaces. We cannot review all of them now. Eventually, when we have to use a class, we will indicate in which namespace it exists.
As mentioned already, we saw in Lesson 5 that we could create a new class using the Add New Class option from the main menu, the Solution Explorer, or the Class View. If you use one of those techniques, the studio will also add other namespaces. For now, we will accept that code "as is".
All of the data types we have used so far are represented by classes in the .NET Framework. This means that they are equipped with methods. These classes are defined in the System namespace. The classes of these data types are defined as:
C# Data Type | Equivalent .NET Class | | C# Data Type | Equivalent .NET Class |
bool | Boolean | | char | Char |
byte | Byte | | sbyte | SByte |
short | Int16 | | ushort | UInt16 |
int | Int32 | | uint | UInt32 |
long | Int64 | | ulong | UInt64 |
float | Single | | double | Double |
decimal | Decimal | | | |
This means that, if you don't want to use the data types we have reviewed so far, you can use the class that is defined in the System namespace. To use one of those classes, type its name. Here is an example:
class Operations
{
public double Addition()
{
Double a;
Double b;
Double c;
a = 128.76;
b = 5044.52;
c = a + b;
return c;
}
}
Because the regular names of data types we introduced in the previous lessons are more known and familiar, we will mostly use them.
Because the data types are defined as classes, they are equipped with methods. One of the methods that each one of them has is called ToString. As its name implies, it is used to convert a value to a string.
|
No comments:
Post a Comment