Methods Fundamentals

Introduction

A method is a function that is created as a member of a class. To put it another way, when a function is made a member of a class, it is called a member function or more precisely a method.

Practical LearningPractical Learning: Introducing the Methods of a Class

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the middle list, click ASP.NET Web Application (.NET Framework) and set the project Name to PayrollPreparation01
  4. Click OK
  5. In the New ASP.NET Web Application dialog box, click Empty and click OK
  6. In the Solution Explorer, make sure PayrollPreparation01 is selected. If not, click it.
    On the main menu, click Project -> New Folder
  7. Type Content and press Enter
  8. In the Solution Explorer, make sure the Content folder is selected. If not, click it.
    On the main menu, click Project -> Add New Item...
  9. In the left frame of the Add New Item dialog box, make sure Web is selected. If not, click it.
    In the middle list, click Style Sheet
  10. Change the file Name to Site
  11. Press Enter
  12. Create some styles as follows:
    body {
        margin: 0;
        background-color: #ffffff;
    }
    
    h1 { font-size: 1.58em; }
    h2 { font-size: 1.28em; }
    
    .container {
        margin: auto;
        width: 300px;
    }
    
    table       { width:       100%;   }
    .emphasize  { font-weight: bold;   }
    .left-col   { width:       120px;  }
    h1, h2      { text-align:  center; }
  13. In the Solution Explorer, right-click PayrollPreparation01 -> Add -> New Item...
  14. In the left frame of the Add New Item dialog box, click Code
  15. In the middle frame, click Code File
  16. Change the file Name to TimeSheet
  17. Click Add
  18. To create a class, type the following code:
    public class TimeSheet
    {
        public decimal Week1TimeWorked;
        public decimal Week2TimeWorked;
    }

Introduction to Creating a Method

The primary formula to create a method is:

options return-type method-name(){}

You can omit or start with one or more options. In future lessons, we will find out what options are available.

A void Method

Like a function, a method is made to solve a problem. A simple method doesn't produce a value. Such a method starts with the void keyword.

The Name of a Method

Like everything else, a function or method must have a name. In our lessons:

The name of a method is followed by parentheses.

Author Note

New Convention:

From now on, in our lessons, to refer to a method that belongs to a class, we may use the convention

class-name.method-name

This means that we are referring to the method method-name that is a member of the class class-name.

The Body of a Method

As mentioned for a function, the body of a method starts immediately after its parentheses and it is delimited by curly brackets { and }. In that body, you can define the desired behavior.

Practical LearningPractical Learning: Creating a Method

As mentioned for a class, the section between the curcly brackets of a function or method is referred to as its body. This is where you will include code for the function. If the function contains many lines of code, the brackets should be used on different lines.

The Access Modifier of a Method

As mentioned for fields, a method can be made public, private, or internal:

If the access level is not specified, the method is considered private. If you want the method to be access outside the class, mark it as public or internal using the same rules we reviewed previously. To make your code easier to read, you should mark each method with an access level. Here are examples:

class House
{
    public string PropertyType;
    public int    Bedrooms;
    public decimal MarketValue;

    private void ProtectFromBadWeather()
    {
    }

    public void ShowPropertyCharacteristics()
    {
    }
}

Practical LearningPractical Learning: Specifying the Access Modifier of a Method

Accessing the Members of a Class in a Method

When you have created a method in a class, in the body of the method, you can access any member of the class by name.

Practical LearningPractical Learning: Accessing the Members of a Class in a Method

Calling a Method

As mentioned for a function, to use a method, you must call it. As mentioned for the fields of a class, if you create a private method, it can be accessed by only members of the same class. On the other hand, after creating a public or internal method, to access it outside the class, declare a variable of the class and use the period operator to access the method.

Practical LearningPractical Learning: Calling a Method

  1. To create a file, in the Solution Explorer, right-click PayrollPreparation01 -> Add -> New Item...
  2. In the left list of the Add New Item dialog box, under Visual C# and under the Web node, click Razor
  3. In the middle list, click Web Page (Razor v3)
  4. Change the Name to Index
  5. Click Add
  6. Change the code as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="~/Content/Site.css" />
    <title>Fun Department Store - Payroll Preparation</title>
    </head>
    <body>
    @{ 
        TimeSheet ts = new TimeSheet();
    
        ts.Initialize();
    }
    
    <div class="container">
        <h1>Fun Department Store</h1>
        <h2>Payroll Preparation</h2>
    
        <table>
            <tr>
                <td colspan="2" class="emphasize">Time Worked</td>
            </tr>
            <tr>
                <td class="left-col emphasize">Week 1:</td>
                <td>@ts.Week1TimeWorked</td>
            </tr>
            <tr>
                <td class="emphasize">Week 2:</td>
                <td>@ts.Week2TimeWorked</td>
            </tr>
        </table>
    </div>
    </body>
    </html>
  7. To execute the application, on the main menu, click Debug -> Start Without Debugging

    Calling a Method

  8. Close the browser and return to your programming environment

Introduction to Parameters and Arguments

Introduction to the Parameters of a Function or Method

Like a function, a method may need some paramerters (as external values) to perform its action. To create a parameter, in the parantheses of the method, enter the data type and a name for each parameter. Here is an example of a method that will need one value as a string:

class House
{
    private void ProtectFromBadWeather(string typeOfRoof)
    {
    }
}

The combination of data type and name that you provide to the method is called a parameter. In the body of the method, you can use the parameter or ignore it.

Practical LearningPractical Learning: Creating a Parameterized Method

Calling a Method of One Parameter

When calling a method that uses a parameter, you must pass an argument. There are various ways you can pass an argument to a method. If you have the value you want to use, provide it in the parentheses of the method. If the value is stored in a variable, you can pass the name of the variable to the method.

Practical LearningPractical Learning: Calling a Method that Uses a Parameter

  1. Access the Index.cshtml file and change its document as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="~/Content/Site.css" />
    <title>Fun Department Store - Payroll Preparation</title>
    </head>
    <body>
    @{
        decimal hourlySalary = 0;
        TimeSheet ts = new TimeSheet();
    
        if (IsPost)
        {
            hourlySalary = Request["txtHourlySalary"].AsDecimal();
            ts.Week1TimeWorked = Request["txtWeek1TimeWorked"].AsDecimal();
            ts.Week2TimeWorked = Request["txtWeek2TimeWorked"].AsDecimal();
    
            ts.CalculateBiweeklySalary(hourlySalary);
        }
    }
    
    <div class="container">
        <h1>Fun Department Store</h1>
        <h2>Payroll Preparation</h2>
    
        <form name="frmPayrollPreparation" method="post">
            <table>
                <tr>
                    <td class="left-col emphasize">Hourly Salary:</td>
                    <td><input type="text" name="txtHourlySalary" value="@hourlySalary" /></td>
                </tr>
                <tr>
                    <td colspan="2" class="emphasize">Time Worked</td>
                </tr>
                <tr>
                    <td class="left-col emphasize">Week 1:</td>
                    <td><input type="text" name="txtWeek1TimeWorked" value="@ts.Week1TimeWorked" /></td>
                </tr>
                <tr>
                    <td class="emphasize">Week 2:</td>
                    <td><input type="text" name="txtWeek2TimeWorked" value="@ts.Week2TimeWorked" /></td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td><input type="submit" name="btnCalculate" value="Calculate" /></td>
                </tr>
                <tr>
                    <td class="emphasize">Biweekly Salary:</td>
                    <td><input type="text" name="txtBiweeklySalary" value="@ts.TotalBiweeklySalary.ToString("F")" /></td>
                </tr>
            </table>
        </form>
    </div>
    </body>
    </html>
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging

    Calling a Method that Uses a Parameter

  3. In the Hourly Salary text box, type a number such as 27.85
  4. In the Week 1 text box, type a number such as 37.50
  5. In the Week 2 text box, type a number such as 41.00
  6. Click the Calculate button:

    Calling a Method that Uses a Parameter

  7. Close the browser and return to your programming environment

A Method With Various Parameters

Like a function, a method can use various parameters. When creating such a method, in its parentheses, provide each parameter by its data type and a name. The parameters are separated by commas. The parameters can be of the same type. Here is an example:

class TimeSheet
{
    public void ShowTimeWorked(string startTime, string endTime)
    {

    }
}

The parameters can also be of different types. Here is an example of a method that uses 3 parameters:

class TimeSheet
{
    public void ShowTimeWorked(string startTime, int timeWorked, string endTime)
    {

    }
}

As mentioned earlier, you don't have to use the parameters in the body of the method if you don't have use for it. Otherwise, in the body of the method, you can use the parameters any appropriate way you want.

Author Note

New Convention:

From now on, in our lessons, to refer to a method that belongs to a class, we may use the convention

class-name.method-name(parameter(s))

This means that we are referring to the method method-name that is a member of the class class-name. The item in the parentheses will refer to the parameter(s) of the method.

In the body of the method, you can ignore one or more parameters, you can ignore all parameters, you can use one or some of the parameters, or you can use all parameters.

Author Note

New Convention:

From now on, in our lessons, we may write "The syntax of this method is" (or something to that effect):

return-type class-name.method-name(parameter(s));

This means that we are providing (reviewing) the return type, the name, and the number of parameters (if any) of a method.

In our new convention, we may terminate the syntax with a semi-colon.

Practical LearningPractical Learning: Creating a Method of many Parameters

Calling a Method of many Parameters

When calling a method that uses many parameters, you must pass an argument for each parameter.

Practical LearningPractical Learning: Calling a Method of many Parameters

  1. Access the Index.cshtml file and change its document as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="~/Content/Site.css" />
    <title>Fun Department Store - Payroll Preparation</title>
    </head>
    <body>
    @{
        decimal hourlySalary = 0;
        TimeSheet ts = new TimeSheet();
    
        if (IsPost)
        {
            hourlySalary = Request["txtHourlySalary"].AsDecimal();
            decimal week1TimeWorked = Request["txtWeek1TimeWorked"].AsDecimal();
            decimal week2TimeWorked = Request["txtWeek2TimeWorked"].AsDecimal();
    
            ts.Initialize(week1TimeWorked, week2TimeWorked);
            ts.CalculateBiweeklySalary(hourlySalary);
        }
    }
    
    <div class="container">
        <h1>Fun Department Store</h1>
        <h2>Payroll Preparation</h2>
    
        <form name="frmPayrollPreparation" method="post">
            <table>
                <tr>
                    <td class="left-col emphasize">Hourly Salary:</td>
                    <td><input type="text" name="txtHourlySalary" value="@hourlySalary" /></td>
                </tr>
                <tr>
                    <td colspan="2" class="emphasize">Time Worked</td>
                </tr>
                <tr>
                    <td class="left-col emphasize">Week 1:</td>
                    <td><input type="text" name="txtWeek1TimeWorked" value="@ts.Week1TimeWorked" /></td>
                </tr>
                <tr>
                    <td class="emphasize">Week 2:</td>
                    <td><input type="text" name="txtWeek2TimeWorked" value="@ts.Week2TimeWorked" /></td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td><input type="submit" name="btnCalculate" value="Calculate" /></td>
                </tr>
                <tr>
                    <td class="emphasize">Biweekly Salary:</td>
                    <td><input type="text" name="txtBiweeklySalary" value="@ts.TotalBiweeklySalary.ToString("F")" /></td>
                </tr>
            </table>
        </form>
    </div>
    </body>
    </html>
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging

    Calling a Method of many Parameters

  3. In the Hourly Salary text box, type a number such as 15.44
  4. In the Week 1 text box, type a number such as 32.00
  5. In the Week 2 text box, type a number such as 35.50
  6. Click the Calculate button:

    Calling a Method of many Parameters

  7. Close the browser and return to your programming environment

The Scope and Lifetime of a Variable

Introduction

The scope of a variable is the extent to which it is available to other members of a class. To manage this, a variable is said to have local or global scope.

Local Variables

A variable is said to be local if it is declared in the body of a method. Here is an example:

class MemberRegistration
{
    private void Create()
    {
        string middleName;
    }
}

When a variable is declared as local, it can be accessed only by code inside the same curly brackets. If you try accessing such a variable outside its curly brackets, you would receive an error.

A Global Variable

A variable is said to be global if it is declared inside in the body of a class and outside the curly brackets of any method. Here is an example:

class MemberRegistration
{
    string strDateOfBirth;

    private void Initialize()
    {

    }

    private void Present()
    {

    }
}

A variable that has been declared globally can be accessed by any code of the same class.

The Scope and Lifetime of an Object

You can declare a variable of a class in the body of a class and initialize it there. Here is an example:

class Student
{
}

class StudentRegistration
{
    Student pupil = new Student();
    
    private void Show()
    {
    }
}

Once this has been done, the object is ready to be used by any method of the same class. As an alternative, you can declare the variable in the body of the class but initialize it in a method of the class. Here is an example:

class Student
{
}

class StudentRegistration
{
    Student pupil;
    
    private void Create()
    {
        pupil = new Student();
    }
    
    private void Show()
    {
    }
}

If you decide to use this technique, before the object can be actually used, you must call the method that initializes the variable, otherwize you may receive an error.

A Method that Returns a Value

Introduction

Like a function, a method can be made to return a value. In fact, a method can also be made to return an object. To indicate that a method is returning a value, when creating that method, the first requirement is that, on the left side of its name, instead of the void keyword, specify a data type. Here is an example:

class Rectangle
{
    public decimal Width;
    public decimal Height;

    public decimal Area()
    {
        
    }
}

The second requirement is that, in the body of the function or a method, you must indicate the value it returns. There are many ways you can do this but the primary technique is that, before the closing curly bracket, type the return keyword followed by the value and a semicolon. Here is an example:

class Rectangle
{
    public decimal Width;
    public decimal Height;

    public decimal Area()
    {
        decimal result = 0.00;

        return result;
    }
}

Otherwise, you can perform any operation in the body of the method and return the desired value. Here is an example:

class Rectangle
{
    public decimal Width;
    public decimal Height;

    public decimal Area()
    {
        decimal result = 0.00M;

        result = Width * Height;

        return result;
    }
}

Practical LearningPractical Learning: Creating a Method that Returns a Value

  1. Access the TimeSheet.cs file and change the CalculateBiweeklySalary() method as follows:
    public class TimeSheet
    {
        public decimal Week1TimeWorked;
        public decimal Week2TimeWorked;
        public decimal HourlySalary;
    
        public void Initialize(decimal hSalary, decimal week1, decimal week2)
        {
            Week1TimeWorked = week1;
            Week2TimeWorked = week2;
            HourlySalary    = hSalary;
        }
    
        public decimal CalculateBiweeklySalary()
        {
            decimal result = 0;
            decimal totalTimeWorked = Week1TimeWorked + Week2TimeWorked;
    
            result = HourlySalary * totalTimeWorked;
    
            return result;
        }
    }

Introducing to Calling a Method that Returns a Value

To use the value that a method returns, you must call that method. If you want, you can assign its value to a local variable.

Practical LearningPractical Learning: Calling a Method that Returns a Value

  1. Access the Index.cshtml file and change its document as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="~/Content/Site.css" />
    <title>Fun Department Store - Payroll Preparation</title>
    </head>
    <body>
    @{
        decimal netPay = 0;
        decimal hourlySalary = 0;
        TimeSheet ts = new TimeSheet();
    
        if (IsPost)
        {
            hourlySalary = Request["txtHourlySalary"].AsDecimal();
            decimal week1TimeWorked = Request["txtWeek1TimeWorked"].AsDecimal();
            decimal week2TimeWorked = Request["txtWeek2TimeWorked"].AsDecimal();
    
            ts.Initialize(hourlySalary, week1TimeWorked, week2TimeWorked);
            netPay = ts.CalculateBiweeklySalary();
        }
    }
    
    <div class="container">
        <h1>Fun Department Store</h1>
        <h2>Payroll Preparation</h2>
    
        <form name="frmPayrollPreparation" method="post">
            <table>
                <tr>
                    <td class="left-col emphasize">Hourly Salary:</td>
                    <td><input type="text" name="txtHourlySalary" value="@hourlySalary" /></td>
                </tr>
                <tr>
                    <td colspan="2" class="emphasize">Time Worked</td>
                </tr>
                <tr>
                    <td class="left-col emphasize">Week 1:</td>
                    <td><input type="text" name="txtWeek1TimeWorked" value="@ts.Week1TimeWorked" /></td>
                </tr>
                <tr>
                    <td class="emphasize">Week 2:</td>
                    <td><input type="text" name="txtWeek2TimeWorked" value="@ts.Week2TimeWorked" /></td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td><input type="submit" name="btnCalculate" value="Calculate" /></td>
                </tr>
                <tr>
                    <td class="emphasize">Biweekly Salary:</td>
                    <td><input type="text" name="txtBiweeklySalary" value="@netPay.ToString("F")" /></td>
                </tr>
            </table>
        </form>
    </div>
    </body>
    </html>
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging

    Calling a Method of many Parameters

  3. In the Hourly Salary text box, type a number such as 18.82
  4. In the Week 1 text box, type a number such as 40.00
  5. In the Week 2 text box, type a number such as 42.50
  6. Click the Calculate button:

    Calling a Method that Returns a Value

  7. Close the browser and return to your programming environment
  8. Access the TimeSheet.cs file and change the CalculateBiweeklySalary() method as follows:
    public class TimeSheet
    {
        public decimal Week1TimeWorked;
        public decimal Week2TimeWorked;
        public decimal HourlySalary;
    
        public void Initialize(decimal hSalary, decimal week1, decimal week2)
        {
            Week1TimeWorked = week1;
            Week2TimeWorked = week2;
            HourlySalary    = hSalary;
        }
    
        public decimal CalculateBiweeklySalary()
        {
            decimal result = 0;
    
            result = HourlySalary * (Week1TimeWorked + Week2TimeWorked);
    
            return result;
        }
    }
  9. Access the Index.cs file and click inside its document to give it focus
  10. To execute the application, on the main menu, click Debug -> Start Without Debugging
  11. Close the browser and return to your programming environment
  12. Access the TimeSheet.cs file and change the CalculateBiweeklySalary() method as follows:
    public class TimeSheet
    {
        public decimal Week1TimeWorked;
        public decimal Week2TimeWorked;
        public decimal HourlySalary;
    
        public void Initialize(decimal hSalary, decimal week1, decimal week2)
        {
            Week1TimeWorked = week1;
            Week2TimeWorked = week2;
            HourlySalary    = hSalary;
        }
    
        public decimal CalculateBiweeklySalary()
        {
            decimal result = HourlySalary * (Week1TimeWorked + Week2TimeWorked);
    
            return result;
        }
    }
  13. Access the Index.cs file and click inside its document to give it focus
  14. To execute the application, on the main menu, click Debug -> Start Without Debugging
  15. Close the browser and return to your programming environment
  16. Access the TimeSheet.cs file and change the CalculateBiweeklySalary() method as follows:
    public class TimeSheet
    {
        public decimal Week1TimeWorked;
        public decimal Week2TimeWorked;
        public decimal HourlySalary;
    
        public void Initialize(decimal hSalary, decimal week1, decimal week2)
        {
            Week1TimeWorked = week1;
            Week2TimeWorked = week2;
            HourlySalary    = hSalary;
        }
    
        public decimal CalculateBiweeklySalary()
        {
            return HourlySalary * (Week1TimeWorked + Week2TimeWorked);
        }
    }
  17. Access the Index.cs file and click inside its document to give it focus
  18. To execute the application, on the main menu, click Debug -> Start Without Debugging
  19. Close the browser and return to your programming environment

A Simple Returning Method with no Body

If you have a method that either contains only one expression or the contents of its body can be resumed to one line, such a method doesn't need a body. Instead, after the parentheses of the method, type => followed by the returning expression. Here is an example:

class Contractor
{
    public int ContractorCode;
    public string FirstName;

    public string LastName;
    public decimal HourlySalary;

    public string ContractorName() => FirstName + " " + LastName;
}

Practical LearningPractical Learning: Using a Method without a Body

  1. Access the TimeSheet.cs file and change the CalculateBiweeklySalary() method as follows:
    public class TimeSheet
    {
        public decimal Week1TimeWorked;
        public decimal Week2TimeWorked;
        public decimal HourlySalary;
    
        public void Initialize(decimal hSalary, decimal week1, decimal week2)
        {
            Week1TimeWorked = week1;
            Week2TimeWorked = week2;
            HourlySalary    = hSalary;
        }
    
        public decimal CalculateBiweeklySalary() => HourlySalary * (Week1TimeWorked + Week2TimeWorked);
    }
  2. Access the Index.cs file and click inside its document to give it focus
  3. To execute the application, on the main menu, click Debug -> Start Without Debugging
  4. Close the browser and return to your programming environment

Techniques of Calling a Method that Returns a Value

You can call a function or method that returns a value as you do for one that is void. If you want to get and use the value returned by the method, you can declare a variable of the return type and assign the call to that variable. The variable would then be carrying the return value of the method and you can use that value any way you want.

<!DOCTYPE html>
<html>
<head>
<title>Department Store</title>
</head>
<body>

@{
    string fullName = "";
    string fName = "Jennifer";
    string lName = "Clarenden";

    Contractor staff = new Contractor();
    staff.FirstName = fName;
    staff.LastName = lName;

    fullName = staff.ContractorName();
}

<h3>=//= Department Store =//=</h3>
<p><span style="font-weight: bold">Employee Name:</span> @fullName</p>
</body>
</html>

In the above code, we first declared a variable in one line and called the method in another line. This is done in case the values of the variable may change. Otherwise, you can declare the variable on the same line where you are calling the method. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Department Store</title>
</head>
<body>

@{
    string fName = "Jennifer";
    string lName = "Clarenden";

    Contractor staff = new Contractor();
    staff.FirstName = fName;
    staff.LastName = lName;

    string fullName = staff.ContractorName();
}

<h3>=//= Department Store =//=</h3>
<p><span style="font-weight: bold">Employee Name:</span> @fullName</p>
</body>
</html>

In the previous two examples, we declared a variable to store the return value of the method. This is done if you plan to use the variable many times, or call the method many times, or if the value of the variable will change more than once. If you are planning to call the method once, of if you don't need to store its value in a variable, you can call the method directly where its value is needed. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Department Store</title>
</head>
<body>

@{
    string fName = "Johnny";
    string lName = "Sonns";

    Contractor staff = new Contractor();
    staff.FirstName = fName;
    staff.LastName = lName;
}

<h3>=//= Department Store =//=</h3>
<p><span style="font-weight: bold">Employee Name:</span> @staff.ContractorName()</p>
</body>
</html>

Having Many Methods that Return the Same Type of Value

Imagine you have a method that returns a value or an expression. Here is an example:

public class Operation
{
    public decimal Number1;
    public decimal Number2;
    public string  Operator;

    public string View()
    {
        return Number1.ToString() + Operator + Number2.ToString();
    }
}

If you need another method that performs the same type of operation and/or returns the same type of value, you don't need to declare a variable to call the first method. Here is an example:

public class Operation
{
    public decimal Number1;
    public decimal Number2;
    public string  Operator;

    public string View()
    {
        return Number1.ToString() + Operator + Number2.ToString();
    }

    public string Add()
    {
        return View();
    }
}

In the same way, you can have other methods that call that method. Here are examples:

public class Operation
{
    public decimal Number1;
    public decimal Number2;
    public string  Operator;

    public string View()
    {
        return Number1.ToString() + Operator + Number2.ToString();
    }

    public string Add()
    {
        return View();
    }

    public string Subtract()
    {
        return View();
    }

    public string Multiply()
    {
        return View();
    }
}

Techniques of Passing Arguments

Accessing a Parameter by Name

If you call a method that takes many arguments, you don't have to use the exact placeholder of each parameter. Instead, you can refer to each argument by the name of its parameter, followed by a colon, and followed by the appropriate value. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Geometry</title>
</head>
<body>
@{ 
    Shape shp = new Shape();

    shp.Describe(name : "Box", width: 200.46m, length : 93.82m);
}
</body>
</html>

Passing an Argument by Value

When calling a method that took one or more arguments, we made sure we provided the necessary value(s) for the parameter(s). This is because an argument is always required and the calling method must provide a valid value when calling such a method. This technique of providing a value for the argument is referred to as passing an argument by value.

Passing an Argument by Reference

When you declare a variable in a program, the compiler reserves some space for that variable in the computer 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 passes it to the called function or method. Although the called method receives the argument's value and can use it in any way it wants, it cannot (permanently) change that value. An alternative is to ask method to modify the value of its parameter. If you want the called method to modify the value of a supplied argument and return the modified value, you can pass the argument using its reference, that is, its address. This is referred to as passing an argument by reference.

To prepare a method that would have a parameter by reference, when defining the method, precede the parameter's data type with the ref keyword. Here is an example:

class BancAccount
{
    public void SetDeposit(ref decimal amount)
    {
    }
}

In the method, you can use or ignore the parameter. Before passing an argument by reference, you must first declare a variable for it and initialize it. When calling the method, precede the argument's name with the ref keyword. here is an example:

@{ 
    decimal deposit = 0.00m;

    if (IsPost)
    {
        BancAccount ba = new BancAccount();

        ba.SetDeposit(ref deposit);
    }
}

The true purpose of passing an argument by reference is to allow the function or method to change the value of the argument. To make this possible, in the method, you can change the value of the argument. Here is an example:

class BancAccount
{
    void SetDeposit(ref decimal amount)
    {
        amount = 450M;
    }
}

This time, the value of the variable is changed after the method has been called.

You can create a method that uses 0, one, or more parameters as reference(s). When we studied the fact that a method can return a value, we saw that a method can return only one value because there is only one return keyword. Fortunately, the ability to use many parameters as references makes it possible for a method to return many values.

Passing an Argument Out

Another technique to pass an argument uses the out keyword. As done for passing by reference, to pass an argument out, in the parentheses of the method, precede the data type of the parameter with the out keyword. Here is an example:

class Exercise
{
    void ProcessWithdrawal(out decimal amount)
    {
        
    }
}

The main difference between the ref and the out keywords is that, if you apply the out keyword to a parameter, you must assign a value to it in the method, whether you will use the argument in the method or not. Here is an example:

class Exercise
{
    void GetWithdrawal(out decimal amount)
    {
        amount = 265.00m;
    }
}

When calling a method that takes an out argument, precede the argument with the out keyword.

As done for the ref keyword, if you pass an argument with out, any modification made on the argument would be kept when the method ends. As mentioned for a ref argument, a method that receives arguments passed with out can be used to return many values, as opposed to returning only one by using the return keyword.

Method Overloading

The ability to have two or more methods with the same name in the same class is referred to as method (or function) overloading.

To perform method overloading, each version of the overloaded method must be different.You cannot use two methods that each uses the same type of parmeter. Consider the following code:

class Geometry
{
    // Unknown Shape
    public decimal CalculateArea()
    {
        return 0M;
    }

    // Square
    public decimal CalculateArea(decimal side)
    {
        return side * side;
    }

    // Circle
    public decimal CalculateArea(decimal radius)
    {
        return radius * radius * 3.14159M;
    }
}

One of the rules of method overloading is that the parameters of the methods can use different data types. Here is an example:

class PayrollPreparation
{
    public decimal CalculateBiweeklySalary()
    {
        return 0.00;
    }

    public decimal CalculateBiweeklySalary(decimal yearlySalary)
    {
        return yearlySalary / 24.00M;
    }

    // A full-time employee with a fixed yearly salary
    public decimal CalculateBiweeklySalary(string monthlySalary)
    {
	    decimal salary = decimal.Parse(monthlySalary);

        return monthlySalary / 2.00M;
    }
}

Another rule of method overloading is that each method can use a different number of parameters.

A Parameter With an Optional Value

Consider the following class:

class SaleItem
{
    public decimal OriginalPrice;

    public decimal CalculatePriceAfterDiscount(decimal discountRate)
    {
        return OriginalPrice - (OriginalPrice * discountRate / 100m);
    }
}

We have learned that if a method uses a parameter, when you call that method, you must provide a value for the argument. There is an exception to this rule. Consider the following code:

<!DOCTYPE html>
<html>
<head>
<title>Fun Department Store - Sales Evaluations</title>
</head>
<body>
    <div align="center">
        <h2>Fun Department Store - Sales Evaluations</h2>

        @{
            string strPriceAfterDiscount = "";
            decimal discountRate = 50.00m; // 50%
            SaleItem si = new SaleItem();

            if (IsPost)
            {
                si.OriginalPrice = Request["txtOriginalPrice"].AsDecimal();

                strPriceAfterDiscount = si.CalculatePriceAfterDiscount(discountRate).ToString("F");
            }
        }

        <form name="fromDepartmentStore" method="post">
            <table>
                <tr>
                    <td style="width: 150px; font-weight: bold">Original Price:</td>
                    <td><input type="text" name="txtOriginalPrice" value="@si.OriginalPrice" style="width: 80px" /></td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td><input type="submit" name="txtCalculate" value="Calculate" /></td>
                </tr>
                <tr>
                    <td style="font-weight: bold">Price after Discount:</td>
                    <td><input type="text" name="txtPriceAfterDiscount" value="@strPriceAfterDiscount" style="width: 80px" /></td>
                </tr>
            </table>
        </form>
    </div>
</body>
</html>

This would produce:

A Parameter With an Optional Value

If you have a method whose argument is usually given the same value, you can give a default value to that parameter. To specify that a parameter has a default value, in the parentheses of the method, after the name of the parameter, assign the default value to it. Here is an example:

class SaleItem
{
    public decimal OriginalPrice;

    public decimal CalculatePriceAfterDiscount(decimal discountRate = 50m)
    {
        return OriginalPrice - (OriginalPrice * discountRate / 100m);
    }
}

When calling the method, you can pass a value for the argument as we have dove so far. If you want to use the default value, omit passing the argument. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Fun Department Store - Sales Evaluations</title>
</head>
<body>
<div align="center">
    <h2>Fun Department Store - Sales Evaluations</h2>

    @{
        string strPriceAfterDiscount = "";
        SaleItem si = new SaleItem();

        if (IsPost)
        {
            si.OriginalPrice = Request["txtOriginalPrice"].AsDecimal();

            strPriceAfterDiscount = si.CalculatePriceAfterDiscount().ToString("F");
        }
    }

    <form name="fromDepartmentStore" method="post">
        <table>
            <tr>
                <td style="width: 150px; font-weight: bold">Original Price:</td>
                <td><input type="text" name="txtOriginalPrice" value="@si.OriginalPrice" style="width: 80px" /></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="submit" name="txtCalculate" value="Calculate" /></td>
            </tr>
            <tr>
                <td style="font-weight: bold">Price after Discount:</td>
                <td><input type="text" name="txtPriceAfterDiscount" value="@strPriceAfterDiscount" style="width: 80px" /></td>
            </tr>
        </table>
    </form>
</div>
</body>
</html>

Notice that the parentheses of the method are empty, which means that the argument was not passed. This code produces the same result as the previous code.

In the same way, you can create a method that uses many parameters and some or all of those parameters can have default values.

If a method uses more than one parameter, you can provide a default value for each and select which ones would have default values. If you want all parameters to have default values, when defining the method, type each name followed by = and followed by the desired value. Here is an example:

class SaleItem
{
    public decimal OriginalPrice;

    public decimal CalculatePriceAfterDiscount(decimal discountRate = 50m)
    {
        return OriginalPrice - (OriginalPrice * discountRate / 100m);
    }

    public decimal CalculateMarkedPrice(decimal price = 200.00m,
                                        decimal tax = 5.75m,
                                        decimal discount = 50.00m)
    {
        decimal markedPrice = 0.00m;

        decimal afterDiscount = price * discount / 100.00m;
        decimal taxValue = afterDiscount * tax / 100.00m;
        markedPrice = afterDiscount + taxValue;

        return markedPrice;
    }
}

Here is a technique of calling the method:

<!DOCTYPE html>
<html>
<head>
<title>Fun Department Store - Sales Evaluations</title>
</head>
<body>
    <div align="center">
        <h2>Fun Department Store - Sales Evaluations</h2>

        @{
            string strMarkedPrice = "";
            SaleItem si = new SaleItem();

            if (IsPost)
            {
                strMarkedPrice = si.CalculateMarkedPrice().ToString("F");
            }
        }

        <form name="fromDepartmentStore" method="post">
            <table>
                <tr>
                    <td style="width: 150px; font-weight: bold">Original Price:</td>
                    <td><input type="text" name="txtOriginalPrice" value="200.00" style="width: 80px" /></td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td><input type="submit" name="txtCalculate" value="Calculate" /></td>
                </tr>
                <tr>
                    <td style="font-weight: bold">Price after Discount:</td>
                    <td><input type="text" name="txtPriceAfterDiscount" value="@strMarkedPrice" style="width: 80px" /></td>
                </tr>
            </table>
        </form>
    </div>
</body>
</html>

This would produce:

A Parameter With an Optional Value

If a method uses more than one parameter and you would like to provide default values for those parameters, the order of appearance of the arguments is important:

Practical LearningPractical Learning: Ending an Application


Previous Copyright © 2001-2019, FunctionX Next