Home

Passing Arguments to a Method of a Class

   

Techniques of Passing Arguments

 

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.

 

ApplicationApplication: 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)
        {
            System.Console.WriteLine("==============================");
            System.Console.WriteLine("Account Information");
            System.Console.WriteLine("------------------------------");
            System.Console.Write("Account #:     ");
            System.Console.WriteLine(acntNbr);
            System.Console.Write("Customer Name: ");
            System.Console.WriteLine(name);
            System.Console.Write("PIN:           ");
            System.Console.WriteLine(PIN);
            System.Console.Write("Balanace:      ");
            System.Console.WriteLine(balance);
            System.Console.WriteLine("==============================");
        }
    
        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:

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

        System.Console.WriteLine("In GetDeposit()");
        System.Console.Write("Amouont: $");
        System.Console.WriteLine(amount);
    }

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

        System.Console.WriteLine("In Main()");
        System.Console.Write("Amouont: $");
        System.Console.WriteLine(amt);

        System.Console.WriteLine("-------------------------");
        exo.GetDeposit(amt);
        System.Console.WriteLine("-------------------------");

        System.Console.WriteLine("Bank in Main()");
        System.Console.Write("Amouont: $");
        System.Console.WriteLine(amt);

        return 0;
    }
}

This would produce:

In Main()
Amouont: $0
-------------------------
In GetDeposit()
Amouont: $450
-------------------------
Bank in Main()
Amouont: $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:

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:

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

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

        System.Console.WriteLine("In Main()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(amt);

        exo.GetDeposit(ref amt);

        System.Console.WriteLine("Bank in Main()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(amt);

        return 0;
    }
}

This would produce:

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:

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

        System.Console.WriteLine("In GetDeposit()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(amount);
    }

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

        System.Console.WriteLine("In Main()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(amt);

        System.Console.WriteLine("-------------------------");
        exo.GetDeposit(ref amt);
        System.Console.WriteLine("-------------------------");

        System.Console.WriteLine("Bank in Main()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(amt);

        return 0;
    }
}

This would produce:

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.

ApplicationApplication: 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)
        {
            System.Console.WriteLine("==============================");
            System.Console.WriteLine("Account Information");
            System.Console.WriteLine("------------------------------");
            System.Console.Write("Account #:     ");
            System.Console.WriteLine(acntNbr);
            System.Console.Write("Customer Name: ");
            System.Console.WriteLine(name);
            System.Console.Write("PIN:           ");
            System.Console.WriteLine(PIN);
            System.Console.Write("Balanace:      ");
            System.Console.WriteLine(balance);
            System.Console.WriteLine("==============================");
        }
    
        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);
    
            System.Console.WriteLine("After a new deposit");
            man.ShowAccountInformation(accountNumber, customerName, 
            			   pin, currentBalance);
    
            withdrawalAmount = man.GetWithdrawal(ref currentBalance);
    
            System.Console.WriteLine("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:

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

The main difference between the ref and the out keywords is that, if you pass an argument with out, you must initialize it (give it a value) in the method, whether you will use the argument in the method or not. Here is an example:

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:

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

        System.Console.WriteLine("In GetDeposit()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(amount);
    }

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

        System.Console.WriteLine("In GetWithdrawal()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(amount);
    }

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

        System.Console.WriteLine("In Main()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(depositAmount);

        System.Console.WriteLine("-------------------------");
        exo.GetDeposit(ref depositAmount);
        System.Console.WriteLine("-------------------------");

        System.Console.WriteLine("Bank in Main()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(depositAmount);

        System.Console.WriteLine("-------------------------");
        exo.GetWithdrawal(out withdrawalAmount);
        System.Console.WriteLine("-------------------------");

        System.Console.WriteLine("Bank in Main()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(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:

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.

Method Overloading

Consider the following function named CalculateArea:

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:

Method Name Encoding
CalculateArea Calculate@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, that 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:

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

    // Square
    public double CalculateArea(double side)
    {
        return side * side;
    }
}
Method Name Argument(s) Encoding
CalculateArea   Calculate@None
CalculateArea double Calculate@Double

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

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();

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

        return 0;
    }
}

This would produce:

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:

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 Name Argument(s) Encoding
CalculateArea   Calculate@None
CalculateArea double Calculate@Double
CalculateArea double Calculate@Double

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

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:

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:

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 Name Argument(s) Encoding
CalculateArea   Calculate@None
CalculateArea double Calculate@Double
CalculateArea double, double Calculate@Double@Double

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

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();

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

        return 0;
    }
}

This would produce:

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 what creating the method. Therefore, another rule of method overloading states that each method must use a different number of argument.

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:

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 Name Argument(s) Encoding
CalculateArea   Calculate@None
CalculateArea double Calculate@Double
CalculateArea double, double Calculate@Double@Double
CalculateArea double, double Calculate@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 argument, 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:

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();

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

        return 0;
    }
}

This would produce:

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

Method overloading is heavily used in the .NET Framework. Therefore, remember its (two, either-or) rules. Fortunately, they are (very) easy: The methods must use either different numbers of arguments or different types of arguments.

When a method is overloaded, when you access it in the Code Editor, the IntelliSense would show a label with 1 of X. The X indicates the number of versions that the method has. Here is an example of a function that has three versions, thus the IntelliSense indicates 1 of 3:

Function Overloading

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.

Optional Arguments

 

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:

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);

        System.Console.WriteLine("After applying the discount");
        System.Console.Write("Final Price = ");
        System.Console.WriteLine(finalPrice);

        return 0;
    }
}

This would produce:

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:

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:

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();

        System.Console.WriteLine("After applying the discount");
        System.Console.Write("Final Price = ");
        System.Console.WriteLine(finalPrice);

        return 0;
    }
}

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

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:

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;

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

        return netPrice;
    }

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

        finalPrice = exo.CalculateNetPrice();

        System.Console.WriteLine("After applying the discount");
        System.Console.Write("Final Price = ");
        System.Console.WriteLine(finalPrice);

        return 0;
    }
}

This would produce:

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);
    
    System.Console.WriteLine("After applying a 25% discount and a 5.50% tax rate");
            System.Console.Write("Final Price = ");
            System.Console.WriteLine(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);
    
    System.Console.WriteLine("After applying a 25% discount and a 5.50% tax rate");
            System.Console.Write("Final Price = ");
            System.Console.WriteLine(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);
    
    System.Console.WriteLine("After applying a 25% discount and a 5.75% tax rate");
            System.Console.Write("Final Price = ");
            System.Console.WriteLine(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:

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);

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

        return 0;
    }
}

This would produce:

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:

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);

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

        return 0;
    }
}

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

ApplicationApplication: Ending the Lesson

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

Previous Copyright © 2010-2016, FunctionX Next