Passing Arguments to a Method of a Class
Passing Arguments to a Method of a Class
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:
class Contractor
{
public string FirstName;
public string LastName;
public string ContractorName() => FirstName + " " + LastName;
public void Present(int nbr, double salary, string status, double time)
{
System.Console.WriteLine("Contractor Details");
System.Console.WriteLine("============================");
System.Console.Write("Contractor Code: ");
System.Console.WriteLine(nbr);
System.Console.Write("Contractor Name: ");
System.Console.WriteLine(ContractorName());
System.Console.Write("Status: ");
System.Console.WriteLine(status);
System.Console.Write("Hourly Rate: ");
System.Console.WriteLine(salary);
System.Console.Write("Time Worked: ");
System.Console.WriteLine(time);
}
}
class Employment
{
static void Main()
{
Contractor staff = new Contractor();
staff.FirstName = "Robert";
staff.LastName = "Dayne";
staff.Present(nbr: 973_405, salary: 15.95, status: "Full Time", time: 38.50);
}
}
This would produce:
Contractor Details ============================ Contractor Code: 973405 Contractor Name: Robert Dayne Status: Full Time Hourly Rate: 15.95 Time Worked: 38.5 Press any key to continue . . .
Remember that, with this technique, you can access the arguments in any order of your choice, as long as each argument is represented by its name. Here is an example:
class Contractor
{
public string FirstName;
public string LastName;
public string ContractorName() => FirstName + " " + LastName;
public void Present(int nbr, double salary, string status, double time)
{
. . . No Change
}
}
class Employment
{
static void Main()
{
Contractor staff = new Contractor();
staff.FirstName = "Robert";
staff.LastName = "Dayne";
staff.Present(status: "Full Time", salary: 15.95, nbr: 973_405, time: 38.50);
}
}
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.
Practical Learning: Passing an Argument by Value
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("=============================="); } static void 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; } }
============================== Account Information ------------------------------ Account #: 248-050842-749 Customer Name: Ann Kelley PIN: 8648 Balanace: 350 ==============================
Passing an Argument by Reference
Consider the following program:
public class Exercise { void GetDeposit(double amount) { amount = 450; System.Console.WriteLine("In GetDeposit()"); System.Console.Write("Amount: $"); System.Console.WriteLine(amount); } static void Main() { double amt = 0; var exo = new Exercise(); System.Console.WriteLine("In Main()"); System.Console.Write("Amount: $"); System.Console.WriteLine(amt); System.Console.WriteLine("-------------------------"); exo.GetDeposit(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: $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 double 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 double amount)
{
}
static void Main()
{
double 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 double amount)
{
amount = 450;
System.Console.WriteLine("In GetDeposit()");
System.Console.Write("Amount: $");
System.Console.WriteLine(amount);
}
static void Main()
{
double 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.
Practical Learning: Passing an Argument by Reference
public class Management { private void ShowAccountInformation(string acntNbr, string name, int 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; } static void Main() { Management man = new Management(); string accountNumber = "248-050842-749"; string customerName = "Ann Kelley"; short pin = 8648; double currentBalance = 350.00; 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; } }
============================== 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 ==============================
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 double 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 double 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 double amount)
{
amount = 450.00M;
System.Console.WriteLine("In GetDeposit()");
System.Console.Write("Amount: $");
System.Console.WriteLine(amount);
}
void GetWithdrawal(out double amount)
{
amount = 265.00m;
System.Console.WriteLine("In GetWithdrawal()");
System.Console.Write("Amount: $");
System.Console.WriteLine(amount);
}
static void Main()
{
double depositAmount = 0M;
double 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.
Consider the following method 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. Let's imagine it looks like this:
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, 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:
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 void 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 void 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 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:
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 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:
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:
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.
A Parameter With an Optional Value
Consider the following class:
class SaleItem
{
public double OriginalPrice;
public double CalculatePriceAfterDiscount(double discountRate)
{
return OriginalPrice - (OriginalPrice * discountRate / 100);
}
}
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:
class SaleItem
{
public double OriginalPrice;
public double CalculatePriceAfterDiscount(double discountRate)
{
return OriginalPrice - (OriginalPrice * discountRate / 100);
}
}
class DepartmentStore
{
static void Main()
{
double priceAfterDiscount = 0.00;
double discountRate = 50.00; // 50%
SaleItem si = new SaleItem();
si.OriginalPrice = 124.95;
priceAfterDiscount = si.CalculatePriceAfterDiscount(discountRate);
System.Console.WriteLine("Fun Department Store -Sales Evaluations");
System.Console.Write("Original Price: ");
System.Console.WriteLine(si.OriginalPrice);
System.Console.Write("Price after Discount: ");
System.Console.WriteLine(priceAfterDiscount);
}
}
This would produce:
Fun Department Store -Sales Evaluations Original Price: 124.95 Price after Discount: 62.475 Press any key to continue . . .
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 double OriginalPrice;
public double CalculatePriceAfterDiscount(double discountRate = 50)
{
return OriginalPrice - (OriginalPrice * discountRate / 100);
}
}
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:
class SaleItem { public double OriginalPrice; public double CalculatePriceAfterDiscount(double discountRate = 50) { return OriginalPrice - (OriginalPrice * discountRate / 100); } } class DepartmentStore { static void Main() { double priceAfterDiscount = 0.00; SaleItem si = new SaleItem(); si.OriginalPrice = 124.95; priceAfterDiscount = si.CalculatePriceAfterDiscount(); System.Console.WriteLine("Fun Department Store -Sales Evaluations"); System.Console.Write("Original Price: "); System.Console.WriteLine(si.OriginalPrice); System.Console.Write("Price after Discount: "); System.Console.WriteLine(priceAfterDiscount); } }
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 double OriginalPrice;
public double CalculatePriceAfterDiscount(double discountRate = 50)
{
return OriginalPrice - (OriginalPrice * discountRate / 100);
}
public double CalculateMarkedPrice(double price = 200.00,
double tax = 5.75,
double discount = 50.00)
{
double markedPrice = 0.00;
double afterDiscount = price * discount / 100.00;
double taxValue = afterDiscount * tax / 100.00;
markedPrice = afterDiscount + taxValue;
return markedPrice;
}
}
Here is a technique of calling the method:
class SaleItem
{
public double OriginalPrice;
public double CalculatePriceAfterDiscount(double discountRate = 50)
{
return OriginalPrice - (OriginalPrice * discountRate / 100);
}
public double CalculateMarkedPrice(double price = 200.00,
double tax = 5.75,
double discount = 50.00)
{
double markedPrice = 0.00;
double afterDiscount = price * discount / 100.00;
double taxValue = afterDiscount * tax / 100.00;
markedPrice = afterDiscount + taxValue;
return markedPrice;
}
}
class DepartmentStore
{
static void Main()
{
SaleItem si = new SaleItem();
si.OriginalPrice = 200.00;
double priceAfterDiscount = si.CalculatePriceAfterDiscount();
double markedPrice = si.CalculateMarkedPrice();
System.Console.WriteLine("Fun Department Store -Sales Evaluations");
System.Console.Write("Original Price: ");
System.Console.WriteLine(si.OriginalPrice);
System.Console.Write("Price after Discount: ");
System.Console.WriteLine(priceAfterDiscount);
System.Console.Write("Marked Price: ");
System.Console.WriteLine(markedPrice);
}
}
This would produce:
Fun Department Store -Sales Evaluations Original Price: 200 Price after Discount: 100 Marked Price: 105.75 Press any key to continue . . .
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 Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2019, FunctionX | Next |
|