Home

Namespaces and Code Organization

 

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 LearningPractical Learning: Introducing Inheritance

 
  1. Start Microsoft Visual Web Developer
  2. To create a new web site, on the main menu, click File -> New Web Site...
  3. Make sure the Language is set to Visual C#.
    Click the second box to the right of Location, delete the suggested name of the web site and replace it with geometry9
  4. Click OK
  5. In the Solution Explorer, right-click Default.aspx and click Rename
  6. Type index.aspx and press Enter
 

Creating a Namespace

To create a namespace, you start with the namespace keyword followed by the name of the section. 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
    {
    }
}
 

Practical LearningPractical Learning: Creating a Namespace

 
  1. On the main menu, click Website -> Add New Item...
  2. In the Templates list, click Class
  3. Replace the suggested name with Square
  4. Click Add
  5. Read the message box that comes up and click Yes
  6. Change the class as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    /// <summary>
    /// Summary description for Square
    /// </summary>
    /// 
    namespace Quadrilateral
    {
        public class Square
        {
            public double sd;
    
            public Square()
            {
                this.sd = 0.00;
            }
    
            public Square(double side)
            {
                this.sd = side;
            }
    
            public virtual double Area()
            {
                return this.sd * this.sd;
            }
        }
    }
  7. Save the first

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:

<%@ Page Language="C#" %>

<html>
<head>
<title>Exercise</title>
</head>
<body>

<%
    Business.House Property = new Business.House();

    Property.PropertyNumber = "D294FF";
    Property.Price = 425880;

    Response.Write("=//= Altair Realty =//=");
    Response.Write("<br>Properties Inventory");
    Response.Write("<br>Property #: ");
    Response.Write(Property.PropertyNumber);
    Response.Write("<br>Market Value: ");
    Response.Write(Property.Price);
%>

</body>
</html>

Practical LearningPractical Learning: Accessing the Members of a Namespace

 
  1. Click the index.aspx tab
  2. To access the method, change the code as follows:
     
    <%@ Page Language="C#"
             AutoEventWireup="true" 
             CodeFile="index.aspx.cs"
             Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>Geometric Shapes</title>
    </head>
    <body>
    
    <%
        // Showing the square
        var Card = new Quadrilateral.Square(35.14);
    
        Response.Write("=-=Square Characteristics=-=");
        Response.Write("<br>Side: ");
        Response.Write(Card.sd);
        Response.Write("<br>Area: ");
        Response.Write(Card.Area());
    %>
    
    </body>
    </html>
  3. Press Ctrl + F5 to see the result
     
    Cylinder
  4. Return to your programming environment

Namespace Nesting

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 Dealer
    {
    }
}

In the example above, the Dealer 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.

Characteristics of Inheritance

 

Namespaces and Inheritance

Imagine you had created a class named Person as follows:

public class Person
{
    private string _name;
    private string _gdr;

    public Person()
    {
	this._name = "Not Available";
	this._gdr  = "Unknown";
    }

    public Person(string name, string gender)
    {
	this._name = name;
	this._gdr  = gender;
    }
}

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
namespace HighSchool
{
	public class Teacher : People.Person
	{
		private string _pos;

		public Teacher()
		{
			this._pos = "Staff Member";
		}

		public Teacher(string pos)
		{
			this._pos     = pos;
		}
	}
}

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:

People.Person man = new People.Person("Hermine Sandt", "Male");
HighSchool.Teacher staff = new HighSchool.Teacher("Vice Principal");

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:

using People;
using HighSchool;

class Exercise
{
    public void Use()
    {
	Person man = new Person("Hermine Sandt", "Male");
	Teacher staff = new Teacher("Vice Principal");
    }
}
 

Practical LearningPractical Learning: Inheriting From a Namespace

 
  1. On the main menu, click Website -> Add New Item...
  2. In the Templates list, click Class
  3. Replace the suggested name with Cube
  4. Click Add
  5. Change the class as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    /// <summary>
    /// Summary description for Cube
    /// </summary>
    namespace Volumes
    {
        public class Cube : Quadrilateral.Square
        {
            public Cube()
            {
                this.sd = 0.00;
            }
    
            public Cube(double side)
            {
                this.sd = side;
            }
    
            public new double Area()
            {
                return this.sd * this.sd * 6;
            }
    
            public double Volume()
            {
                return this.sd * this.sd * this.sd;
            }
        }
    }
  6. Click the index.aspx tab
  7. To access the method, change the code as follows:
     
    <%@ Page Language="C#"
             AutoEventWireup="true" 
             CodeFile="index.aspx.cs"
             Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>Geometric Shapes</title>
    </head>
    <body>
    
    <%
        // Showing the square
        var Card = new Quadrilateral.Square(35.14);
    
        Response.Write("=-=Square Characteristics=-=");
        Response.Write("<br>Side: ");
        Response.Write(Card.sd);
        Response.Write("<br>Area: ");
        Response.Write(Card.Area());
        Response.Write("<p></p>");
    
        // Showing the cube
        var Box = new Volumes.Cube(62.24);
    
        Response.Write("=-=Cube Characteristics=-=");
        Response.Write("<br>Side: ");
        Response.Write(Box.sd);
        Response.Write("<br>Area: ");
        Response.Write(Box.Area());
        Response.Write("<br>Volume: ");
        Response.Write(Box.Volume());
    %>
    
    </body>
    </html>
  8. Press Ctrl + F5 to see the result
     
    Cylinder
  9. Return to your programming environment

Using a Namespace

We saw that, to call an object or a method that is part of a namespace, you must "qualify" that method or 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. Here is an example:

using Quadrilateral;

namespace Volumes
{
    public class Cube : Square
    {
        public Cube()
        {
            this.sd = 0.00;
        }

        public Cube(double side)
        {
            this.sd = side;
        }

        public new double Area()
        {
            return this.sd * this.sd * 6;
        }

        public double Volume()
        {
            return this.sd * this.sd * this.sd;
        }
    }
}

With the using keyword, you can include as many external namespaces as necessary. Here are examples:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Quadrilateral;

/// <summary>
/// Summary description for Cube
/// </summary>


namespace Volumes
{
    public class Cube : Square
    {
        public Cube()
        {
            this.sd = 0.00;
        }

        public Cube(double side)
        {
            this.sd = side;
        }

        public new double Area()
        {
            return this.sd * this.sd * 6;
        }

        public double Volume()
        {
            return this.sd * this.sd * this.sd;
        }
    }
}

Introduction to Built-In Namespaces

 

Introduction to the System Namespace

To make programming in C# a little easier, many classes ship with it and they are created in various namespaces of the .NET Framework. Each namespace in C# is used to provide a specific set of classes. The most regularly used namespace in the C# language is called System.

Introduction to the .NET Support of Data Types

In C# (unlike many other languages such as C/C++, Pascal, etc), all of the data types we have used so far are in fact complete classes. 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 these types, type the System namespace followed by a period. Then type the equivalent class you want to use. 

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.

C# Language Accessories

 

Unsafe Code

When C# was invented, one of its biggest goals was to avoid some of the difficulties of C/C++. Among them was the use of pointers. C/C++ uses pointers to refer to the area in memory where a value is located. C# highly avoids pointers and takes over memory management as opposed to letting the programmer take care of that aspect of an application. You can still use pointers in C# in extreme cases when you judge them necessary.

Because the C# compiler is in charge of managing the memory used by the values of an application, pointers are said to be unsafe. If you want to use a pointer in your application, you must precede the name of every method that uses unsafe code with the unsafe keyword.

Code Editor Region Delimiter

The Visual Web Developer provides various techniques to assist you with code writing and management. The characteristics include color-coded words, intuitive indentation, delimitation of sections of code, etc.

There are - buttons on the left side of some lines of code. These allow you to collapse a section of code if you think you don't need to see it. To do this, you can click the - button. If you click that - button, it changes into a + button.

The + button allows you to expand a hidden code section. This behavior of creating + and - buttons is part of the Code Editor of Microsoft Visual Studio (yes, many other programming environments use that behavior also). To create these sections, the Code Editor follows some rules. For example, it looks for the start and end of such items as directives, namespaces, classes, methods, etc.

Besides, or instead of, the sections of code created by the Code Editor, if you want, you can create your own sections. To do this, start the section with

#region Whatever

and end it with

#endregion Whatever

When and where you start, the #region expression is required. On the right side of this expression, you can type anything you want on the line. To end the section, type #endregion, followed by anything you want. Consider the following example:


class House
{
    void Create()
    {
    }
}

#region These are classes used for Student Registration
class Car
{
    void Build()
    {
    }
}

class Student
{
    void Register()
    {
    }
}
#endregion We can just stop it here

class Program
{
    static void Main()
    {
    }
}

You don't have to type anything on the right side of #endregion. After creating the region, the Code Editor would display a - button to the left side of #region with a line from there to the left of #endregion. This then allows you to expand and collapse that section at will.

We mentioned that you didn't have to type anything on the right side of #endregion and you could leave it empty. In our example, notice that there is a rectangle with gray lines around the string that follows #region. This rectangle doesn't cover the string that follows #endregion. This means that if you don't type anything on the right side of #endregion, that section on the right side the #region line would not show.

 
 

Previous Copyright © 2009-2011 C# Key Next