Home

The Methods of a Class

 

Methods Fundamentals

 

Introduction

When you create a class, the fields are meant to describe it. An action performed by a class is called a method.

Sometimes, a method must produce a result. If it doesn't, then it is considered void. If the method doesn't produce a result, type void to its left.

Here is an example:

<script runat="server">
public class House
{
    internal long PropertyNumber;
    internal string PropertyType;
    internal uint Bedrooms;
    internal double Value;

    void Display()
    {
    }
}
</script>

In the same way, you can create as many methods as you want in a class.

Like a member variable, a method can be marked as private (if it will be accessed only by members of the same class), internal, or public.

After creating a method, in its body delimited by its curly brackets, you can define the desired behavior. 

If you create your class in its own file using Microsoft Visual Studio or Microsoft Visual Web Developer, to help you manage the methods of a class, the Code Editor is equipped with two combo boxes.

The left combo box, called Types, displays the classes that are part of the project. The right combo box, named Members, 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.

HomePractical Learning: Creating a Method of a Class

  1. Start Microsoft Visual Studio or Microsoft Visual Web Developer
  2. Open the DepartmentStore1 project from the previous lesson
  3. Access the DepartmentStore.cs file
  4. To add a method to the DepartmentStore class, change it as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    /// <summary>
    /// Summary description for DepartmentStore
    /// </summary>
    public class DepartmentStore
    {
        public long StockNumber;
        public char Category;
        public string ItemName;
        public decimal UnitPrice;
    
        public void CreateItem()
        {
            StockNumber = 792475;
            Category = 'M';
            ItemName = "Lightweight Jacket";
            UnitPrice = 185.00M;
        }
    }
  5. Save 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.

HomePractical Learning: Using a Method of a Class

  1. Access the index.aspx file and change it 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>Department Store - Inventory</title>
    </head>
    <body>
    
    <%
        DepartmentStore dptStore = new DepartmentStore();
    
        dptStore.CreateItem();
    %>
    
    <%
        Response.Write("<pre>Department Store" + "<br />");
        Response.Write("Item #:     " + dptStore.StockNumber + "<br />");
        Response.Write("Category:   " + dptStore.Category + "<br />");
        Response.Write("Name:       " + dptStore.ItemName + "<br />");
        Response.Write("Unit Price: " + dptStore.UnitPrice + "</pre>");
    %>
    
    </body>
    </html>
  2. Press Ctrl + F5 to preview the web page. This would produce:
     
    Department Store
  3. Return to your programming environment

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.

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:

<script runat="server">
public class House
{
    internal long PropertyNumber;
    internal string PropertyType;
    internal uint Bedrooms;
    internal double Value;

    public string Describe()
    {
    }
}
</script>

After a method has performed its assignment, it must clearly demonstrate that it is returning a value. To show 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:

<script runat="server">
public class House
{
    public long PropertyNumber;
    public string PropertyType;
    public uint Bedrooms;
    public double Value;

    public string Describe()
    {
	return "";
    }
}
</script>

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

When a method returns a value, the compiler considers such a method as if it were a regular value. This means that you can use the Reponse.Write() method to display its value. To do this, simply type the name of the method and its parentheses in the Reponse.Write() method.

Otherwise, you must declare an instance of the class and use that instance to access the method using the period operator. Here is an example:

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

<html>
<head>

<script runat="server">
public class House
{
    public long PropertyNumber;
    public string PropertyType;
    public uint Bedrooms;
    public double Value;

    public string Describe()
    {
	string description;

    	description = "<pre>=//= Altair Realty =//=<br />" +
                       "Properties Inventory<br />" +
                       "Property #:     " + PropertyNumber + "<br />" + 
                       "Property Type:  " + PropertyType + "<br />" + 
                       "Bedrooms:       " + Bedrooms + "<br />" + 
                       "Market Value:   " + Value + "</pre>";

	return description;
    }
}
</script>

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

<%
    House property = new House();

    property.PropertyNumber = 283795;
    property.PropertyType = "Single Family";
    property.Bedrooms = 4;
    property.Value = 652880;
%>

<% Response.Write(property.Describe()); %>

</body>
</html>

This would produce:

House

We have seen how to call a method from the parentheses of another method that needs its result. In the same way, a method that returns a value can be assigned to a variable of the same type.

 
 
 
     

Characteristics of Members of a Class

 

Constants

You can create a constant variable in a class. To do this, type the const keyword to the left of the variable. 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

Practical LearningPractical Learning: Using this

  1. Access the DepartmentStore.cs file and, to use this, change the class as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    /// <summary>
    /// Summary description for DepartmentStore
    /// </summary>
    public class DepartmentStore
    {
        public long StockNumber;
        public char Category;
        public string ItemName;
        public decimal UnitPrice;
    
        public void CreateItem()
        {
            this.StockNumber = 792475;
            this.Category = 'M';
            this.ItemName = "Lightweight Jacket";
            this.UnitPrice = 185.00M;
        }
    }
  2. Save the file
  3. Return to the browser and refresh
  4. Return to your programming environment

Methods' Arguments

 

Introduction

In order to perform its assignment, a method may  need a value from outside of its body. Such a value is called an argument. The value is provided in the parentheses of the method. The argument is specified using a data type and a name.

Here is an example of an argument:

<script runat="server">
public class House
{
    public void SetPropertyNumber(long number)
    {
    }
}
</script>

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.

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:

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

<html>
<head>

<script runat="server">
public class House
{
    public void SetPropertyNumber(long number)
    {
    }
}
</script>

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

<%
    House property = new House();

    property.SetPropertyNumber(283795);
%>

</body>
</html>

A method that takes an argument can also declare its own local variable(s). 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. 

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

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. You can call a 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:

<script runat="server">
public class House
{
    public void SetPropertyNumber(out long number)
    {
    }
}
</script>

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. Here is an example:

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

<html>
<head>

<script runat="server">
public class House
{
    public void SetPropertyNumber(out long number)
    {
	number = 283795;
    }
}
</script>

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

<%
    House property = new House();
    long nbr;

    property.SetPropertyNumber(out nbr);
%>

</body>
</html>

Method Overloading

Method overloading consists of using the same name for more than one method. Of course, there are rules you must observe:

  • The methods must have the same name
  • The methods must have either different types of arguments or different numbers of arguments
 
 
   
 

Previous Copyright 2009 FunctionX Next