ASP.NET

Passing Arguments to a Method of a Class

lf you call a method that takes many arguments, you don't have to use the exact placeholder of each argument. Instead, you can refer to each argument by…

14 min read3,023 words36 code samples

html Lesson 08: Passing Arguments to a Method of a Class

Passing Arguments to a Method of a Class#

Techniques of Passing and Accessing Parameters#

Calling an Argument by Name#

When calling a method that accepts multiple arguments, you aren't strictly required to follow the exact order of placeholders to supply values. One useful approach is to refer to each argument by its specific name.

You can either start typing until the name of an argument is selected or you can double-click from the list. As mentioned already, after the name of the argument, add a colon and a value for the argument. In the same way, you can access any argument by its name and give it a value, separate them with commas. Here is an example:

C#
class Exercise
{
    void ShowEmployee(long employeeNumber, string fullName, char gender, double hourlySalary)
    {
            Response.Write("Employee Record");
            Response.Write("-----------------------------");
            Response.Write("Employee #:    ");
            Response.Write(employeeNumber);
            Response.Write("Full Name:     ");
            Response.Write(fullName);
            Response.Write("Gender:        ");
            Response.Write(gender);
            Response.Write("Hourly Salary: ");
            Response.Write(hourlySalary);
    }

    static int Main()
    {
        Exercise exo = new Exercise();

        exo.ShowEmployee(fullName: "Annette Greens", hourlySalary: 16.85, employeeNumber: 519427, gender: 'F');

        return 0;
    }
}

This would produce:

C#
Employee Record
-----------------------------
Employee #:    519427
Full Name:     Annette Greens
Gender:        F
Hourly Salary: 16.85
Press any key to continue . . .

Method Overloading#

Consider the following function named CalculateArea:

C#
public class Geometry
{
    double CalculateArea()
    {
        return 0D;
    }
}

When you create a method in a class and when you build the project, the compiler creates a list of those methods. This list is called a virtual table. In the table, a method is encoded using its name. Let's imagine it looks like this:

Method NameEncoding
CalculateAreaCalculate@None

If the method has an argument, the table contains the data type of that argument. Neither the return type of the method nor the name(s) of the argument(s) is important. If the class contains methods that have different names, they are easily distinguishable (because they have different names). Sometimes, for one reason or another, you may want to have different methods that do a similar job with slight differences (it will be your job to define what the differences are and why). One way you can indicate that the methods accomplish the same purpose is to have them use the same name. The ability to have two or more methods with the same name in the same class is referred to as method overloading. To perform method overloading, which we will refer to in our lessons as overloading a method, when creating the virtual table, each entry in the list must be unique. As mentioned already, the return type of a method is not entered. So you cannot base the differences on it. If you try creating two methods and none takes an argument, obviously you cannot distinguish them in the table. The solution is that one of them should take an argument. Here is an example:

C#
public class Geometry
{
    // Unknown Shape
    public double CalculateArea()
    {
        return 0D;
    }

    // Square
    public double CalculateArea(double side)
    {
        return side * side;
    }
}
Method NameArgument(s)Encoding
CalculateAreaCalculate@None
CalculateAreadoubleCalculate@Double

Obviously this time, each method has a different encoding. Here is an example of using the above code:

C#
public class Geometry
{
    // Unknown Shape
    public double CalculateArea()
    {
        return 0D;
    }

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

public class Exercise
{
    static int Main()
    {
        Geometry geo = new Geometry();

            Response.Write("Geometric Shapes");
            Response.Write("Calculation of Areas");
            Response.Write("Square: ");
            Response.Write(geo.CalculateArea(26.38));

        return 0;
    }
}

This would produce:

C#
Geometric Shapes
Calculation of Areas
Square: 695.9044
Press any key to continue . . .

Remember that the name of an argument is not part of its encoding in the virtual table. Therefore, you cannot use two methods that each takes the same type of argument. Consider the following code:

C#
public class Geometry
{
    // Unknown Shape
    public double CalculateArea()
    {
        return 0D;
    }

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

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

This would result in:

Method NameArgument(s)Encoding
CalculateAreaCalculate@None
CalculateAreadoubleCalculate@Double
CalculateAreadoubleCalculate@Double

As a result, when you build the project, the compiler would produce the following error:

C#
Error 1 Type 'Geometry' already defines a member called 'CalculateArea'
with the same parameter types	
C:\Exercise1\Exercise.cs	16	19	Overloading

One of the rules of method overloading is that the method can have different types of arguments. Here is an example:

C#
public class Geometry
{
    // Unknown Shape
    public double CalculateArea()
    {
        return 0D;
    }

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

    // Circle
    public float CalculateArea(float radius)
    {
        return radius * radius * 3.14159f;
    }
}

In many cases, you will not want to simply pass a different type of argument. We mentioned that, in the virtual table, the data type of the argument is entered. What if each method takes a different number of argument? Consider the following example:

C#
public class Geometry
{
    // Unknown Shape
    public double CalculateArea()
    {
        return 0D;
    }

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

    // Rectangle
    public double CalculateArea(double length, double height)
    {
        return length * height;
    }
}

This would result in:

Method NameArgument(s)Encoding
CalculateAreaCalculate@None
CalculateAreadoubleCalculate@Double
CalculateAreadouble, doubleCalculate@Double@Double

Notice that the encoding of the second and the third methods is different. Here is an example of calling the methods:

C#
public class Geometry
{
    // Unknown Shape
    public double CalculateArea()
    {
        return 0D;
    }

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

    // Rectangle
    public double CalculateArea(double length, double height)
    {
        return length * height;
    }
}

public class Exercise
{
    static int Main()
    {
        var geo = new Geometry();

            Response.Write("Geometric Shapes");
            Response.Write("Calculation of Areas");
            Response.Write("Square:    ");
            Response.Write(geo.CalculateArea(26.38));
            Response.Write("Rectangle: ");
            Response.Write(geo.CalculateArea(39.17, 26.38));

        return 0;
    }
}

This would produce:

C#
eometric Shapes
alculation of Areas
quare:    695.9044
ectangle: 1033.3046
ress any key to continue . . .

Although we are using two double arguments for the third methd, the arguments can be of any type. It will be your decision when creating the method. Therefore, another rule of method overloading is that each method must use a different number of arguments. One of the characteristics of most computer languages, including C-based languages (C++, Java, C#, etc) and others (Pascal, Visual Basic, etc) is that you don't have to use an argument in its method. You can use this feature to create two versions of a method that should have the same behavior: you can pass an argument that you will not use but that results in a distinguished entry in the virtual table. Consider the following code:

C#
public class Geometry
{
    // Unknown Shape
    public double CalculateArea()
    {
        return 0D;
    }

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

    // Rectangle
    public double CalculateArea(double length, double height)
    {
        return length * height;
    }

    // Circle
    public double CalculateArea(double radius, int unused)
    {
        return radius * radius * 3.14159;
    }
}

This would result in:

Method NameArgument(s)Encoding
CalculateAreaCalculate@None
CalculateAreadoubleCalculate@Double
CalculateAreadouble, doubleCalculate@Double@Double
CalculateAreadouble, doubleCalculate@Double@Integer

Notice that the encodings are distinct. Remember that, normally, you need only one value to calculate the areas of a square or a circle. To distinguish their calculations in our code, we passed a second argument to the area of the circle. We named the argument "unused" but you can use any name (one of the differences between C++ and C# is that in the former, you can omit a name; therefore, if this code were written in C++, we would not have to name the argument). When calling the method that takes two arguments, you must pass a value for the second argument. Since the method will not use the argument, you can pass any value, as long as it is conform to the type. Here is an example of using the above code:

C#
public class Geometry
{
    // Unknown Shape
    public double CalculateArea()
    {
        return 0D;
    }

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

    // Rectangle
    public double CalculateArea(double length, double height)
    {
        return length * height;
    }

    // Circle
    public double CalculateArea(double radius, int unused)
    {
        return radius * radius * 3.14159;
    }
}

public class Exercise
{
    static int Main()
    {
        var geo = new Geometry();

            Response.Write("Geometric Shapes");
            Response.Write("Calculation of Areas");
            Response.Write("Square:    ");
            Response.Write(geo.CalculateArea(26.38));
            Response.Write("Rectangle: ");
            Response.Write(geo.CalculateArea(39.17, 26.38));
            Response.Write("Circle:    ");
            Response.Write(geo.CalculateArea(26.38, 0));

        return 0;
    }
}

This would produce:

C#
Geometric Shapes
Calculation of Areas
Square:    695.9044
Rectangle: 1033.3046
Circle:    2186.246303996
Press any key to continue . . .

The .NET Framework makes extensive use of method overloading. Keep in mind its two core principles: overloaded methods must either have a different count of arguments or use arguments of differing data types.

To select one of the versions, you can press the down arrow key or you can start typing the value of the argument until the right version is shown.

An Argument With an Optional Value#

We have learned that if a method takes an argument, when you call that method, you must provide a value for the argument. There is an exception to this rule. If you have a method whose argument is usually given the same value, you can give a default value to that argument. Consider the following code:

C#
public class Exercise
{
    double? CalculateNetPrice(double? discountRate)
    {
        double? origPrice = 125.55;

        return origPrice - (origPrice * discountRate / 100);
    }

    static int Main()
    {
        var exo = new Exercise();
        double? finalPrice = null;
        double? discount = 15; // That is 25% = 25

        finalPrice = exo.CalculateNetPrice(discount);

            Response.Write("After applying the discount");
            Response.Write("Final Price = ");
            Response.Write(finalPrice);

        return 0;
    }
}

This would produce:

C#
After applying the discount
Final Price = 106.7175
Press any key to continue . . .

To specify that an argument has a default value, in the parentheses of the method, after the name of the argument, assign the default value to it. Here is an example:

C#
public class Exercise
{
    double? CalculateNetPrice(double? discountRate = 25)
    {
        double? origPrice = 125.55;

        return origPrice - (origPrice * discountRate / 100);
    }
}

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

C#
public class Exercise
{
    double? CalculateNetPrice(double? discountRate = 25)
    {
        double? origPrice = 125.55;

        return origPrice - (origPrice * discountRate / 100);
    }

    static int Main()
    {
        var exo = new Exercise();
        double? finalPrice = null;

        finalPrice = exo.CalculateNetPrice();

            Response.Write("After applying the discount");
            Response.Write("Final Price = ");
            Response.Write(finalPrice);

        return 0;
    }
}

Notice that the parentheses of the method are empty, which means that the argument was not passed. This would produce:

C#
After applying the discount
Final Price = 94.1625
Press any key to continue . . .

In the same way, you can create a method that takes many arguments and some or all of those arguments can have default values. If a method takes more than one argument, you can provide a default argument for each and select which ones would have default values. If you want all arguments to have default values, when defining the method, type each name followed by = and followed by the desired value. Here is an example:

C#
public class Exercise
{
    double? CalculateNetPrice(double? tax = 5.75,
                              double? discount = 25,
                              double? origPrice = 245.55)
    {
        double? discountValue = origPrice * discount / 100;
        double? taxValue = tax / 100;
        double? netPrice = origPrice - discountValue + taxValue;

            Response.Write("Original Price: $");
            Response.Write(origPrice);
            Response.Write("Discount Rate: ");
            Response.Write(discount);
            Response.Write("%");
            Response.Write("Tax Amount: $");
            Response.Write(tax);

        return netPrice;
    }

    static int Main()
    {
        var exo = new Exercise();
        double? finalPrice = null;

        finalPrice = exo.CalculateNetPrice();

            Response.Write("After applying the discount");
            Response.Write("Final Price = ");
            Response.Write(finalPrice);

        return 0;
    }
}

This would produce:

C#
Original Price: $245.55
Discount Rate: 25%
Tax Amount: $5.75
After applying the discount
Final Price = 184.22
Press any key to continue . . .

If a method takes more than one argument and you would like to provide default values for those parameters, the order of appearance of the arguments is very important.

  • If a method takes two arguments, you can declare it with default values. We already know how to do that. If you want to provide a default value for only one of the arguments, the argument that would have a default value must be the second. When calling such a function, if you supply only one argument, the compiler would assign its value to the first parameter in the list and ignore assigning a value to the second: public class Exercise { double? CalculateNetPrice(double? taxRate, double? discountRate = 25) { double? origPrice = 185.95; double? discountValue = origPrice * discountRate / 100; double? taxValue = taxRate / 100; double? netPrice = origPrice - discountValue + taxValue; return netPrice; } static int Main() { double? finalPrice; double? taxRate = 5.50; // = 5.50% Exercise exo = new Exercise(); finalPrice = exo.CalculateNetPrice(taxRate); Response.Write("After applying a 25% discount and a 5.50% tax rate"); Response.Write("Final Price = "); Response.Write(finalPrice); return 0; } } Here is an example of running the program: After applying a 25% discount and a 5.50% tax rate Final Price = 139.5175 Press any key to continue . . . If you define the function and assign a default value to the first argument, if you provide only one argument when calling the function, you would receive an error. Consider the following code: public class Exercise { double? CalculateNetPrice(double? discountRate = 25, double? taxRate) { double? origPrice = 185.95; double? discountValue = origPrice * discountRate / 100; double? taxValue = taxRate / 100; double? netPrice = origPrice - discountValue + taxValue; return netPrice; } static int Main() { double? finalPrice; double? taxRate = 5.50; // = 5.50% Exercise exo = new Exercise(); finalPrice = exo.CalculateNetPrice(taxRate); Response.Write("After applying a 25% discount and a 5.50% tax rate"); Response.Write("Final Price = "); Response.Write(finalPrice); return 0; } } This would produce two errors as: Error 1 Optional parameters must appear after all required parameters C:\Exercises\Bank\Exercise.cs 3 70 Bank
  • If the method receives more than two arguments and you would like only some of those arguments to have default values, the arguments that have default values must be at the end of the list. Regardless of how many arguments would or would not have default values, start the list of arguments with those that would not use default values. Here is an example: public class Exercise { double? CalculateNetPrice( double? origPrice, double? taxRate = 5.75, double? discountRate = 25 ) { double? discountValue = origPrice * discountRate / 100; double? taxValue = taxRate / 100; double? netPrice = origPrice - discountValue + taxValue; return netPrice; } } When calling the method, you can provide a value for only the argument(s) that do(es) not have a default value: public class Exercise { double? CalculateNetPrice(double? origPrice, double? taxRate = 5.75, double? discountRate = 25) { double? discountValue = origPrice * discountRate / 100; double? taxValue = taxRate / 100; double? netPrice = origPrice - discountValue + taxValue; return netPrice; } static int Main() { double? originalPrice = 375.95; double? finalPrice; Exercise exo = new Exercise(); finalPrice = exo.CalculateNetPrice( originalPrice ); Response.Write("After applying a 25% discount and a 5.75% tax rate"); Response.Write("Final Price = "); Response.Write(finalPrice); return 0; } } Here is an example of running the program: After applying a 25% discount and a 5.75% tax rate Final Price = 282.02 Press any key to continue . . . As you can see, the argument(s) that has(have) default value(s) must be last in the list of arguments

Calling an Argument By Name#

We saw that if you create a method that takes more than one argument and not all arguments have default values, when calling the method, if you don't want to provide (a) value(s) for the argument(s) with (an) optional value(s), you can just pass the value(s) of the non-optional argument. Imagine you have a method that takes two or more optional arguments. In C++, if you want to provide a value for the second optional argument, you must first pass a value for the first optional argument. Even if you want to use the default value of the first argument, you must pass it. Here is an example:

C#
public class Exercise
{
    double? CalculateNetPrice(double? origPrice,
                              double? taxRate = 5.75,
                              double? discountRate = 25)
    {
        double? discountValue = origPrice * discountRate / 100;
        double? taxValue = taxRate / 100;
        double? netPrice = origPrice - discountValue + taxValue;

        return netPrice;
    }

    static int Main()
    {
        double? finalPrice;

        Exercise exo = new Exercise();

        finalPrice = exo.CalculateNetPrice(375.95, 5.75, 40);

            Response.Write("Original Price: 375.95");
            Response.Write("Tax Rate:       5.75%");
            Response.Write("Discount Rate:  40%");
            Response.Write("Final Price:    ");
            Response.Write(finalPrice);

        return 0;
    }
}

This would produce:

C#
Original Price: 375.95
Tax Rate:       5.75%
Discount Rate:  40%
Final Price:    225.6275
Press any key to continue . . .

Imagine you want to skip one optional argument to use its default value but you want to pass a value for the second, third, etc argument. To do this, in the parentheses of the method of you are calling, type the name of the argument, followed by a colon and the desired value, which is the same as calling an argument by name. Here is an example:

C#
public class Exercise
{
    double? CalculateNetPrice(double? origPrice,
                              double? taxRate = 5.75,
                              double? discountRate = 25)
    {
        double? discountValue = origPrice * discountRate / 100;
        double? taxValue = taxRate / 100;
        double? netPrice = origPrice - discountValue + taxValue;

        return netPrice;
    }

    static int Main()
    {
        double? finalPrice;

        Exercise exo = new Exercise();

        finalPrice = exo.CalculateNetPrice(discountRate : 40, origPrice : 375.95);

            Response.Write("Original Price: 375.95");
            Response.Write("Tax Rate:       5.75%");
            Response.Write("Discount Rate:  40%");
            Response.Write("Final Price:    ");
            Response.Write(finalPrice);

        return 0;
    }
}

With this technique, you can ignore the optional arguments whose values you don't want to provide. Application: Ending the Lesson

  1. Close your programming environment
  2. When asked whether you want to save, click No

Passing Arguments by Value or by Reference#

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 argument(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. Application: Passing an Argument by Value

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click FILE -> New -> Project...
  3. In the middle list, click Empty Project
  4. Change the Name to NationalBank1 and press Enter
  5. To create a new file, in the Solution Explorer, right-click NationalBank1 -> Add -> New Item...
  6. In the middle list, click Code File
  7. Change the Name of the file to Management
  8. Click Add
  9. In the empty Management.cs file, type the following: public class Management { private void ShowAccountInformation(string acntNbr, string name, short PIN, double balance) { Response.Write("=============================="); Response.Write("Account Information"); Response.Write("------------------------------"); Response.Write("Account #: "); Response.Write(acntNbr); Response.Write("Customer Name: "); Response.Write(name); Response.Write("PIN: "); Response.Write(PIN); Response.Write("Balanace: "); Response.Write(balance); Response.Write("=============================="); } public static int Main() { Management man = new Management(); string accountNumber = "248-050842-749"; string customerName = "Ann Kelley"; short pin = 8648; double currentBalance = 350.00D; man.ShowAccountInformation(accountNumber, customerName, pin, currentBalance); System.Console.ReadKey(); return 0; } }
  10. To execute, press F5 ============================== Account Information ------------------------------ Account #: 248-050842-749 Customer Name: Ann Kelley PIN: 8648 Balanace: 350 ==============================
  11. After seeing the result, press Enter to close the DOS window

Passing an Argument by Reference#

Consider the following program:

C#
public class Exercise
{
    void GetDeposit(decimal amount)
    {
        amount = 450;

            Response.Write("In GetDeposit()");
            Response.Write("Amount: $");
            Response.Write(amount);
    }

    static int Main()
    {
        decimal amt = 0;
        var exo = new Exercise();

            Response.Write("In Main()");
            Response.Write("Amount: $");
            Response.Write(amt);

            Response.Write("-------------------------");
        exo.GetDeposit(amt);
            Response.Write("-------------------------");

            Response.Write("Bank in Main()");
            Response.Write("Amount: $");
            Response.Write(amt);

        return 0;
    }
}

This would produce:

C#
In Main()
Amount: $0
-------------------------
In GetDeposit()
Amount: $450
-------------------------
Bank in Main()
Amount: $0
Press any key to continue . . .

Notice that the value of the argument is the same before and after calling the GetDeposit() method. When you declare a variable in a program, the compiler reserves an amount of space for that variable. If you need to use that variable somewhere in your program, you can simply access 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. An alternative is to call a method to modify the value of an 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 can pass the argument using its reference. To pass an argument as a reference, when defining the method, precede the argument's data type with the ref keyword. Here is an example:

C#
public class Exercise
{
    void GetDeposit(ref decimal amount)
    {
    }
}

In the method, you can use or ignore the argument. When calling the method, precede the argument's name with the ref keyword. here is an example:

C#
public class Exercise
{
    void GetDeposit(ref decimal amount)
    {
    }

    static int Main()
    {
        decimal amt = 0;
        var exo = new Exercise();

            Response.Write("In Main()");
            Response.Write("Amount: $");
            Response.Write(amt);

        exo.GetDeposit(ref amt);

            Response.Write("Bank in Main()");
            Response.Write("Amount: $");
            Response.Write(amt);

        return 0;
    }
}

This would produce:

C#
In Main()
Amount: $0
Bank in Main()
Amount: $0
Press any key to continue . . .

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

C#
public class Exercise
{
    void GetDeposit(ref decimal amount)
    {
        amount = 450;

            Response.Write("In GetDeposit()");
            Response.Write("Amount: $");
            Response.Write(amount);
    }

    static int Main()
    {
        decimal amt = 0;
        var exo = new Exercise();

            Response.Write("In Main()");
            Response.Write("Amount: $");
            Response.Write(amt);

            Response.Write("-------------------------");
        exo.GetDeposit(ref amt);
            Response.Write("-------------------------");

            Response.Write("Bank in Main()");
            Response.Write("Amount: $");
            Response.Write(amt);

        return 0;
    }
}

This would produce:

C#
In Main()
Amount: $0
-------------------------
In GetDeposit()
Amount: $450
-------------------------
Bank in Main()
Amount: $450
Press any key to continue . . .

Notice that this time, the value of the variable is changed after the function has been called. 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. When we studied the fact that a method can return a value, we saw that a function can return only one value because there is only one return keyword. Fortunately, the ability to pass many arguments by reference makes it possible for a method to return many values. Application: Passing an Argument by Reference

  1. Change the Management.cs file as follows: public class Management { private void ShowAccountInformation(string acntNbr, string name, short PIN, double balance) { Response.Write("=============================="); Response.Write("Account Information"); Response.Write("------------------------------"); Response.Write("Account #: "); Response.Write(acntNbr); Response.Write("Customer Name: "); Response.Write(name); Response.Write("PIN: "); Response.Write(PIN); Response.Write("Balanace: "); Response.Write(balance); Response.Write("=============================="); } private double GetDeposit(ref double amount) { double deposit = 225.55; amount = amount + deposit; return deposit; } private double GetWithdrawal(ref double amount) { double withdrawal = 265.25d; amount = amount - withdrawal; return withdrawal; } public static int Main() { Management man = new Management(); string accountNumber = "248-050842-749"; string customerName = "Ann Kelley"; short pin = 8648; double currentBalance = 350.00D; double? depositAmount = null; double? withdrawalAmount = null; man.ShowAccountInformation(accountNumber, customerName, pin, currentBalance); depositAmount = man.GetDeposit(ref currentBalance); Response.Write("After a new deposit"); man.ShowAccountInformation(accountNumber, customerName, pin, currentBalance); withdrawalAmount = man.GetWithdrawal(ref currentBalance); Response.Write("After a withdrwal"); man.ShowAccountInformation(accountNumber, customerName, pin, currentBalance); System.Console.ReadKey(); return 0; } }
  2. Press F5 to execute ============================== Account Information ------------------------------ Account #: 248-050842-749 Customer Name: Ann Kelley PIN: 8648 Balanace: 350 ============================== After a new deposit ============================== Account Information ------------------------------ Account #: 248-050842-749 Customer Name: Ann Kelley PIN: 8648 Balanace: 575.55 ============================== After a withdrwal ============================== Account Information ------------------------------ Account #: 248-050842-749 Customer Name: Ann Kelley PIN: 8648 Balanace: 310.3 ==============================
  3. Press Enter to close the DOS window

Passing an Argument Out#

Another option consists of passing an argument using 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 argument with the out keyword. Here is an example:

C#
public class Exercise
{
    void GetWithdrawal(out decimal amount)
    {
        
    }
}

The primary distinction between ref and out is that a variable passed using out does not need to be initialized before the method call occurs.

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

C#
public class Exercise
{
    void GetDeposit(ref decimal amount)
    {
        amount = 450.00M;

            Response.Write("In GetDeposit()");
            Response.Write("Amount: $");
            Response.Write(amount);
    }

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

            Response.Write("In GetWithdrawal()");
            Response.Write("Amount: $");
            Response.Write(amount);
    }

    static int Main()
    {
        decimal depositAmount = 0M;
        decimal withdrawalAmount = 0M;
        var exo = new Exercise();

            Response.Write("In Main()");
            Response.Write("Amount: $");
            Response.Write(depositAmount);

            Response.Write("-------------------------");
        exo.GetDeposit(ref depositAmount);
            Response.Write("-------------------------");

            Response.Write("Bank in Main()");
            Response.Write("Amount: $");
            Response.Write(depositAmount);

            Response.Write("-------------------------");
        exo.GetWithdrawal(out withdrawalAmount);
            Response.Write("-------------------------");

            Response.Write("Bank in Main()");
            Response.Write("Amount: $");
            Response.Write(withdrawalAmount);

        return 0;
    }
}

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. This would produce:

C#
In Main()
Amount: $0
-------------------------
In GetDeposit()
Amount: $450.00
-------------------------
Bank in Main()
Amount: $450.00
-------------------------
In GetWithdrawal()
Amount: $265.00
-------------------------
Bank in Main()
Amount: $265.00
Press any key to continue . . .

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. Previous Copyright © 2008-2016, FunctionX Next