Home

The Methods of a Class

 

Methods Fundamentals

 

Introduction

When you create a class, the fields are meant to describe it. For a class that represents a square, an example is the side:

public class Square
{
    public double Side;
}

Besides the characteristics used to describe it, an object can also perform actions or assignments. An action performed by a class is called a method. A method is simply a section of code that takes care of a particular detail for the functionality of the class. To create a method, you specify its name, which follows the rules we defined for variables. The name of a method is followed by parentheses.

A method's job is to carry a specific assignment within a program. As such, it could provide a value once the assignment has been carried. In some cases, a method must produce a result. If it doesn't, then it is considered void. The type of value that a method can provide (or return) is written on the left side of the method name. If the method doesn't produce a result, type void to its left. The assignment that a method carries is included between an opening curly bracket "{" and a closing curly bracket "}". Here is an example:

public class Square
{
    public double Side;

    void Display()
    {
    }
}

After creating a method, in its body delimited by its curly brackets, you can define the desired behavior. In the same way, you can create as many methods as you want in a class. To assist you with managing the methods of a class, you can use the two com boxes of the the Code Editor. The Types combo box displays the classes that are part of the project. The Members combo box displays the members of the class that is selected in the Types combo box. If you select an item from the Members combo box, the caret would be displayed on its declaration in the file.

Accessing a Method

After creating a method, you can access it outside of its class. You do this following the same rules used to access a field, using the period operator. Unlike a field, the name of a class must be followed by parentheses.

Code Editor Region Delimiter

Microsoft Visual C# 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. Consider the following contents of a code section in the Code Editor, based on what we have reviewed so far:

public class Geometry
{
    public void Initiate()
    {
    }
}

public class Square
{
    private double sd;

    public void CreateSquare()
    {
    }

    public void Results
    {
    }

    public void ShowPerimeter()
    {
    }

    public void ShowArea
    {
    }
}

public class Rectangle
{
    private double Length;
    private double Base;

    public void Initialize()
    {
    }

    public void Descibe
    {
    }

    public void CalculatePerimeter()
    {
    }

    public void CalculateArea()
    {
    }
}

public class Box
{
    private double Base;
}

Some lines of this code would display - buttons on their left. This allows you to collapse a section of code by clicking the - button. When a - button has been clicked, it becomes a + button, which allows you to expand the section of code. Besides these sections delimited by - buttons and created intuitively by the Code Editor, you also can create your own sections.

In a typical code, you can create sections of code so you that you can expand or collapse a code section. This behavior of creating + and - buttons is part of the Code Editor of Microsoft Visual Studio. 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 section of code in  the Code Editor:

public class Geometry
{
	public void Initiate()
	{
	}
}

#region These are classes used to process flat shapes
public class Square
{
    private double sd;

    public void CreateSquare()
    {
    }

    public void Results
    {
    }

    public void ShowPerimeter()
    {
    }

    public void ShowArea
    {
    }
}

public class Rectangle
{
    private double Length;
    private double Base;

    public void Initialize()
    {
    }

    public void Descibe
    {
    }

    public void CalculatePerimeter()
    {
    }

    public void CalculateArea()
    {
    }
}

#endregion This is the end of flat shapes

public class Box
{
    private double Base;
}

This would appear as follows:

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 allows you to expand and collapse that section at will:

You don'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.

The Static Members of a Class

 

Static Fields

Imagine you create a class called Book. To access it in another method, you can declare its variable, as we have done so far. A variable you have declared of a class is also called an instance of the class. In the same way, you can declare various instances of the same class as necessary.

All of the member variables and methods of classes we have used so far are referred to as instance members because, in order to access them, you must have an instance of a class declared in another class in which you want to access them.

C# allows you to declare a class member and refer to it regardless of which instance of an object you are using. Such a member variable is called static. To declare a member variable of a class as static, type the static keyword on its left. Whenever you have a static member, in order to refer to it, you must "qualify" it in the class in which you want to call it. Qualifying a member means you must specify its class. Here is an example:

public class Square
{
    public static double Side;
}

public class Geometry
{
    void ShowSquare()
    {
         double OneSide = Square.Side;
    }
}

Notice that when a member variable has been declared as static, you don't need an instance of the class to access that member variable outside of the class. Based on this, if you declare all members of a class as static, you don't need to declare a variable of their class in order to access them.

Static Methods

Like a member variable, a method of a class can be defined as static. Consequently, a static method can access any member of the class regardless of the instance if there are many instances of the class declared.

To define a method as static, type the static keyword to its left. Here is an example:

public class Book
{
    private static string Title;
    static private string Author;
    private static int    Pages;
    static private double Price;

    static public void CreateBook()
    {
	Title  = "Psychology and Human Evolution";
	Author = "Jeannot Lamm";
	Pages  = 472;
	Price  = 24.95;
    }
}

Static Classes

A static class:

  1. Is a class whose members must be accessed without an instance of the class. In other words, the members of a static class must be accessed directly from (using the name of) the class, using the period operator
  2. Is a class whose members must be created as static. In other words, you cannot add a non-static member to a static class: all members, except for constants, must be static

To create a static class, precede the class keyword with the static keyword. Based on the above two rules, here is an example:

public static class Square
{
    public static double Side;

    public static void ShowPerimeter()
    {
    }
}

Characteristics of Members of a Class

 

Constants

Unlike C/C++, in C#, you can create a constant variable in a class. As done in Lesson 7 when studying variables, to declare a constant variable, type the const keyword to the left of the variable. Once again, when declaring a constant, you must initialize it with an appropriate constant value.

this Instance

If a class contains fields and methods, the (non-static) field members are automatically available to the method(s) of the class, even fields that are private. When accessing a field or a method from another method of the class, to indicate that the member you are accessing belongs to the same class, you can precede it with the this member and the period operator.

When using the this member variable, you can access any member of a class within any method of the same class. There are rules you must observe when using this:

  • The this member can never be declared: it is automatically implied when you create a class
  • this cannot be used in a class A to access a member of class B. 
  • this cannot be used in a static method

Methods and Local Variables

 

Introduction

In the body of a method, you can declare one or more variables that would be used only by the method. A variable declared in the body of a method is referred to as a local variable. The variable cannot be accessed outside of the method it belongs to. After declaring a local variable, it is made available to the method and you can use it as you see fit, for example, you can assign it a value prior to using it.

 

Practical Learning Practical Learning: Using a Method's Local Variables

  1. Start Microsoft Visual Studio 2005 if necessary and, to create a web site, on the main menu, click File -> New -> Web Site...
  2. Make sure ASP.NET Web Site is selected.
    Make sure the Language combo box is set to Visual C#.
    In the combo box on the left side of Browse, delete the default name of the web site and replace it with geometry5  
  3. Click OK
  4. In the Solution Explorer, right-click Default.aspx and click Rename
  5. Set the name to index.aspx and press Enter
  6. In the Solution Explorer, right-click C:\...\geometry5\ and click New Folder
  7. Type images as the name of the new folder and press Enter
  8. Copy the following picture to your My Documents folder:
     
  9. In the Solution Explorer, right-click images and click Add Existing Item...
  10. Locate the folder where you saved the picture, select each and press Enter
  11. To create a CSS file, in the Solution Explorer, right-click C:\...\geometry5\ and click Add New Item...
  12. In the Templates list, click Style Sheet
  13. Set the name to geometry and press Enter
  14. Complete the file as follows:
     
    body
    {
    	font-size: 11pt;
    	color: black;
    	font-family: Verdana, Tahoma, Arial, Sans-Serif;
    }
    
    hr { color: #0000ff }
    
    .maintitle
    {
    	color: blue;
    	font-family: 'Times New Roman' , Garamond, Georgia, Serif;
    	text-align: center;
    	font-size: 24pt;
    	font-weight: bold;
    	text-decoration: none;
    }
    
    .parajust
    {
    	font-family: Verdana, Tahoma, Arial, Sans-Serif;
    	font-size: 10pt;
    	font-weight: normal;
    	text-align: justify;
    }
    
    .centeredtext
    {
    	font-family: Verdana, Tahoma, Arial, Sans-Serif;
    	font-size: 10pt;
    	font-weight: normal;
    	text-align: center;
    }
    
    .centered
    {
    	text-align: center;
    }
    
    .formula
    {
    	font-weight: bold;
    	font-size: 10pt;
    	color: blue;
    	font-family: Verdana, Helvetica, Tahoma, Sans-Serif;
    }
    
    a:link       {
      font-family: Verdana, Helvetica, Arial, Sans Serif;
      color: #0000FF;
      font-size: 10pt;
      font-weight: bold;
      text-decoration: none }
    
    a:alink {
      font-family: Verdana, Helvetica, Arial, Sans Serif;
      color: #FF00FF;
      font-size: 10pt;
      font-weight: bold;
      text-decoration: none }
    
    a:visited
    {
    	font-family: Verdana, Helvetica, Arial, Sans Serif;
    	color: Green;
    	font-size: 10pt;
    	font-weight: bold;
    	text-decoration: none;
    }
    
    a:hover
    {
    	font-family: Verdana, Helvetica, Arial, Sans Serif;
    	color: #FF0000;
    	font-size: 10pt;
    	font-weight: Bold;
    	text-decoration: none;
    }
  15. Click the index.aspx tab to access its file
  16. In the lower-left section of the window, click Design and design the form as follows:
     

    Create the controls as follows:
    Control Text ID
    Label Radius:  
    TextBox   txtRadius
    Label Height:  
    TextBox   txtHeight
    Button Calculate btnCalculate
    Label Base Area:  
    TextBox   txtBaseArea
    Label Lateral Area:  
    TextBox   txtLateralArea
    Label Total Area:  
    TextBox   txtTotalArea
    Label Volume  
    TextBox   txtVolume
  17. In the lower-left section of the window, click Source and change the source code of the web page 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">
    
    <link rel="Stylesheet" type="text/css" href="geometry.css" />
    <title>Geometry: Cylinder</title>
    
    </head>
    <body>
        <form id="frmCylinder" runat="server">
        <div>
            <p class="maintitle">Geometry: Cylinder</p>
            <hr />
            <p class="parajust">A cylinder is a geometric volume whose 
    	base is a circle. The circle is elevated vertically for a 
    	certain height, which produces the volume. A cylinder can 
    	be represented as follows:</p>
            
            <p class="centered"><img src="images/cylinder1.gif" /></p>
    
            <p class="parajust">Because a cylinder has a circular base, 
    	to process it, you should know the radius of the circle:</p>
    
            <p>R: radius</p>
    
            <p class="parajust">Since a cylinder is a vertical volume, 
    	you should know by how much it is elevated. This is referred 
    	to as its height:</p>
    
            <p>H: height</p>
            
            <p class="parajust">Once these values are known, you can use 
    	the following formulas to process a cylinder:</p>
            
            <table>
                <tr>
                    <td style="width: 550px">
                        BaseArea = Radius * Radius * Math.PI</td>
                </tr>
                <tr>
                    <td style="width: 550px">
                        LateralArea = 2 * Math.PI * Radius * Height</td>
                </tr>
                <tr>
                    <td style="width: 550px">
                        TotalArea = 2 * Math.PI * Radius * (Height + Radius)
    		</td>
                </tr>
                <tr>
                    <td style="width: 550px">
                        Volume = Math.PI * Radius * Radius * Height</td>
                </tr>
            </table>
        
        </div><hr />
            <br />
            <table>
                <tr>
                    <td style="width: 104px">
                        <asp:Label ID="Label1" runat="server" Text="Radius:">
    		    </asp:Label></td>
                    <td style="width: 103px">
                        <asp:TextBox ID="txtRadius" 
    				 runat="server" Width="100px">
    		   </asp:TextBox></td>
                    <td style="width: 100px">
                    </td>
                </tr>
                <tr>
                    <td style="width: 104px">
                        <asp:Label ID="Label2"
    			       runat="server" Text="Height:">
    		</asp:Label></td>
                    <td style="width: 103px">
                        <asp:TextBox ID="txtHeight"
    				 runat="server" Width="100px">
    			</asp:TextBox></td>
                    <td style="width: 100px">
                        <asp:Button ID="btnCalculate" runat="server"
    				Text="Calculate" Width="102px" /></td>
                </tr>
                <tr>
                    <td style="width: 104px">
                        <asp:Label ID="Label3"
    			       runat="server" Text="Base Area:">
    		    </asp:Label></td>
                    <td style="width: 103px">
                        <asp:TextBox ID="txtBaseArea" 
    				 runat="server" Width="100px">
    		    </asp:TextBox></td>
                    <td style="width: 100px">
                    </td>
                </tr>
                <tr>
                    <td style="width: 104px">
                        <asp:Label ID="Label4" runat="server"
    			       Text="Lateral Area:">
    		    </asp:Label></td>
                    <td style="width: 103px">
                        <asp:TextBox ID="txtLateralArea" 
    				 runat="server" Width="100px">
    		    </asp:TextBox></td>
                    <td style="width: 100px">
                    </td>
                </tr>
                <tr>
                    <td style="width: 104px">
                        <asp:Label ID="Label5" 
    			       runat="server" 
    			       Text="Total Area:">
    		    </asp:Label></td>
                    <td style="width: 103px">
                        <asp:TextBox ID="txtTotalArea" 
    				 runat="server" Width="100px">
    		    </asp:TextBox></td>
                    <td style="width: 100px">
                    </td>
                </tr>
                <tr>
                    <td style="width: 104px">
                        <asp:Label ID="Label6" 
    			       runat="server" Text="Volume:">
    		    </asp:Label></td>
                    <td style="width: 103px">
                        <asp:TextBox ID="txtVolume"
    				 runat="server" Width="100px">
    		    </asp:TextBox></td>
                    <td style="width: 100px">
                    </td>
                </tr>
            </table>
            <br />
            <table border="0" width="100%">
                <tr>
                    <td>
                        <hr />
                    </td>
                </tr>
                <tr>
                    <td>
                        <p class="centered">
    			Copyright © 2007 NetConsulting, Inc.</p>
                    </td>
                </tr>
                <tr>
                    <td>
                        <hr />
                    </td>
                </tr>
            </table>
        </form>
    </body>
    </html>
  18. To create a new folder, in the Solution Explorer, right-click C:\...\geometry5\ and click New Folder
  19. Type App_Code as the name of the new folder and press Enter
  20. To create a new class, in the Solution Explorer, right-click App_Code and click Add New Item...
  21. In the Templates list, make sure Class is selected; otherwise, click it.
    Set the Name to Cylinder and click Add
  22. To declare a few variables in the class, change the file as follows:
     
    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    /// <summary>
    /// Summary description for Cylinder
    /// </summary>
    public class Cylinder
    {
        private double rad;
        private double hgt;
    }
  23. Save the file

A Method that Returns a Value 

If a method has carried an assignment and must make its result available to other methods or other classes, the method must return a value and cannot be void. To declare a method that returns a value, provide its return type to the left of its name. Here is an example:

class Calculation
{
    public double Operation()
    {
    }
}

After a method has performed its assignment, it must clearly demonstrate that it is returning a value. To do this, you use the return keyword followed by the value that the method is returning. The value returned must be of the same type specified as the return type of the method. Here is an example:

class Calculation
{
    public double Operation()
    {
	return 24.55;
    }
}

A method can also return an expression, provided the expression produces a value that is conform to the return type. Here is an example:

class Calculation
{
    public double Operation()
    {
	return 24.55 * 4.16;
    }
}

When a method returns a value, the compiler considers such a method as if it were a regular value. For example, a method that returns a value can be assigned to a variable of the same type.

Practical Learning Practical Learning: Returning a Value From a Method 

  1. To create methods that return values, change the file as follows:
     
    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    /// <summary>
    /// Summary description for Cylinder
    /// </summary>
    public class Cylinder
    {
        private double rad;
        private double hgt;
    
        public double GetRadius()
        {
            return rad;
        }
    
        public double GetHeight()
        {
            return hgt;
        }
    
        public double CalculateBaseArea()
        {
            return rad * rad * Math.PI;
        }
    
        public double CalculateLateralArea()
        {
            return 2 * Math.PI * rad * hgt;
        }
    
        public double CalculateTotalArea()
        {
            return 2 * Math.PI * rad * (hgt + rad);
        }
    
        public double CalculateVolume()
        {
            return Math.PI * rad * rad * hgt;
        }
    }
  2. Save the file

Methods' Arguments

 

Introduction

A method can perform an assignment that completes the operations of a class. Sometimes, a method would need one or more values in order to carry its assignment. The particularity of such a value or such values is that another method that calls this one must supply the needed value(s). When a method needs a value to complete its assignment, such a value is called an argument.

Like a variable, an argument is represented by its type of value. For example, one method may need a character while another would need a string. Yet another method may require a decimal number. This means that the method or class that calls a method is responsible for supplying the right value, even though a method may have an internal mechanism of checking the validity of such a value.

The value supplied to a method is typed in the parentheses of the method and it's called an argument. In order to declare a method that takes an argument, you must specify its name and the argument between its parentheses. Because a method must specify the type of value it would need, the argument is represented by its data type and a name.

Suppose you want to define a method that adds a certain value to a known number. Since you would have to supply the number, you can define such a method as follows:

class Calculation
{
    public void Add(double number)
    {
    }
}

In the body of the method, you may or may not use the value of the argument. Otherwise, you can manipulate the supplied value as you see fit. Here is an example:

class Calculation
{
    public void Add(double number)
    {
	double result;
	const double local = 14.50;
	result = number + local;
    }
}

When calling a method that takes an argument, you must supply a value for the argument; otherwise you would receive an error. Also, you should/must supply the right value; otherwise, the method may not work as expected and it may produce an unreliable result. Here is an example:

class Calculation
{
    public void Add(double number)
    {
	double result;
	const double local = 14.50;
	result = number + local;
    }

    public void Display()
    {
	double nbr = 228.95;
	
	Add(nbr);
    }
}

A method can take more than one argument. When defining such a method, provide each argument with its data type and a name. The arguments are separated by a comma.

Practical Learning Practical Learning: Passing Arguments

  1. Change the cylinder.cs file as follows:
     
    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    /// <summary>
    /// Summary description for Cylinder
    /// </summary>
    public class Cylinder
    {
        private double rad;
        private double hgt;
    
        public double GetRadius()
        {
            return rad;
        }
    
        public void SetRadius(double radius)
        {
            rad = radius;
        }
    
        public double GetHeight()
        {
            return hgt;
        }
    
        public void SetHeight(double height)
        {
            hgt = height;
        }
    
        public double CalculateBaseArea()
        {
            return rad * rad * Math.PI;
        }
    
        public double CalculateLateralArea()
        {
            return 2 * Math.PI * rad * hgt;
        }
    
        public double CalculateTotalArea()
        {
            return 2 * Math.PI * rad * (hgt + rad);
        }
    
        public double CalculateVolume()
        {
            return Math.PI * rad * rad * hgt;
        }
    }
  2. Click the index.aspx tab to access its file and, in the lower-left section of the window, click Design

Techniques of Passing Arguments

 

Passing an Argument by Value

When calling a methods that takes one or more arguments, we made sure we provided the necessary value. This is because an argument is always required and the calling method must provide a valid value when calling such a method.

Passing an Argument by Reference

When you declare a variable in a program, the compiler reserves an amount of memory space for that variable. If you need to use that variable somewhere in your program, you call it and make use of its value. There are two major issues related to a variable: its value and its location in the memory. The location of a variable in memory is referred to as its address.

If you supply the argument using its name, the compiler only makes a copy of the argumentís value and gives it to the calling method. Although the calling method receives the argumentís value and can use it in any way, it cannot (permanently) alter it. C# allows a calling method to modify the value of a passed argument if you find it necessary. If you want the calling method to modify the value of a supplied argument and return the modified value, you should pass the argument using its reference.

To pass an argument as a reference, when defining and when calling the method, precede the argument's data type with the ref keyword. You can pass 0, one, or more arguments as reference in the program or pass all arguments as reference. The decision as to which argument(s) should be passed by value or by reference is based on whether or not you want the called method to modify the argument and permanently change its value.

Another option consists of passing an argument using the out keyword. Here is an example:

class Exercise
{
    void Initialize(out double n)
    {
	n = 128.44;
    }
}

If you pass an argument with out, any modification made on the argument would be kept when the method ends. When calling a method that takes an out argument, precede the argument with the out keyword. 

Method Overloading

A typical program involves a great deal of names that represent variables and methods of various kinds. The compiler does not allow two variables to have the same name in the same method. Although two methods should have unique names in the same program, a class can have different methods with the same name if you follow some rules. The ability to have various methods with the same name in the same program is referred to as method overloading. To perform overloading, the methods must have different numbers or different type(s) of arguments.

 

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. 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 GeometricShapes
{
}

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 GeometricShapes
{
    class Square
    {
    }
}

Accessing 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 GeometricShapes
{
    public class Square
    {
        public double Side;
    }
}

class Geometry
{
    void ShowSquare()
    {
         GeometricShapes.Square sqr = GeometricShapes.Square();
         
         sqr.Side = 24.55;
    }
}

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 Geometry
{
    namespace FlatShapes
    {
    }
    
    namespace VolumeShapes
    {
    }    
}

In this example, the FlatShapes namespace is nested inside of the Geometry namespace. After creating the desired namespaces, nested or not, you can create the necessary class(es) inside of the desired namespace. Here is an example:

namespace Geometry
{
    namespace FlatShapes
    {
        public class Square
        {
            public double Side;
        }
    }
    
    namespace VolumeShapes
    {
    }    
}

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 Geometry
{
    namespace FlatShapes
    {
        public class Square
        {
            public double Side;
        }
    }
    
    namespace VolumeShapes
    {
    }

    public class Describer
    {
	public void Show()
	{
	}
    }
}

class Program
{
    void Summarize()
    {
        Geometry.Describer desc = new Geometry.Describer();

        desc.Show();

        Geometry.FlatShapes.Square sqr = new Geometry.FlatShapes.Square();
        sqr.Side = 38.425;
    }
}

In the same way, you can nest as many namespaces inside of other namespaces as you judge necessary.

The System Namespace

 

Introduction

To support web development, the .NET Framework provides many classes and they are created in various namespaces. Each namespace in C# is used to provide a specific set of classes. The most regularly used namespace is called System. This namespace contains a list (the definitions) of the data types we introduced in the previous lesson.

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, type using followed by the name of the namespace.

With the using keyword, you can include as many external namespaces as necessary.

.NET Support of Data Types

 

Introduction

All of the data types we introduced in the previous lesson 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, you can type the System namespace followed by a period. Then type the equivalent class you want to use. Here is an example:

class Operations
{
    public void Addition()
    {
	System.Double a;
	System.Double b;
	System.Double c;
		
	a = 128.76;
	b = 5044.52;
	c = a + b;
    }
}

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.

 

 

Previous Copyright © 2007 FunctionX, Inc. Next