References of Values
References of Values
Introduction to Passing an Argument
Passing an Argument by Value
By now, you should know that you can create a function or a method that uses a parameter. Here are examples:
using static System.Console; double Subtract(double a, double b) { return a - b; } double CalculateDiscount(double price, double rate) { return price * rate / 100.00; }
When calling a function or a method that takes one or more arguments, we must provide the necessary value(s) for the parameter(s). This is because an argument is always required and the calling function or method must provide a valid value when calling such a function or a method. This technique of providing a value for the argument is referred to as passing an argument by value. Here are examples:
using static System.Console; double Subtract(double a, double b) { return a - b; } double CalculateDiscount(double price, double rate) { return price * rate / 100.00; } double cost = 149.95; int dRate = 20; double discount = CalculateDiscount(cost, dRate); double markedValue = Subtract(cost, discount); WriteLine("Fun Department Store"); WriteLine("==================================="); WriteLine($"Orignial Price: {cost}"); WriteLine($"Discount Rate: {dRate}%"); WriteLine("-----------------------------------"); WriteLine($"Discount Amount: {discount}"); WriteLine($"Marked Price: {markedValue:F}"); WriteLine("===================================");
This would produce:
Fun Department Store =================================== Orignial Price: 149.95 Discount Rate: 20% ----------------------------------- Discount Amount: 29.99 Marked Price: 119.96 =================================== Press any key to close this window . . .
Practical Learning: Introducing Parameters
using static System.Console;
PreparePayroll();
// -------------------------------------------------------
string GetFirstName()
{
WriteLine("FUN DEPARTMENT STORE");
WriteLine("=======================================================");
WriteLine("Payroll Preparation");
WriteLine("-------------------------------------------------------");
WriteLine("Enter the following pieces of information");
WriteLine("-------------------------------------------------------");
WriteLine("Employee Information");
WriteLine("-------------------------------------------------------");
Write("First Name: ");
string result = ReadLine()!;
return result;
}
string GetLastName()
{
Write("Last Name: ");
string result = ReadLine()!;
return result;
}
double GetBaseRate()
{
Write("Hourly Salary: ");
double wages = double.Parse(ReadLine()!);
return wages;
}
double GetMondayTimeWorked()
{
WriteLine("-------------------------------------------------------");
WriteLine("Time worked");
WriteLine("-------------------------------------------------------");
Write("Monday: ");
double time = double.Parse(ReadLine()!);
return time;
}
double GetTuesdayTimeWorked()
{
Write("Tuesday: ");
double time = double.Parse(ReadLine()!);
return time;
}
double GetWednesdayTimeWorked()
{
Write("Wednesday: ");
double time = double.Parse(ReadLine()!);
return time;
}
double GetThursdayTimeWorked()
{
Write("Thursday: ");
double time = double.Parse(ReadLine()!);
return time;
}
double GetFridayTimeWorked()
{
Write("Friday: ");
double time = double.Parse(ReadLine()!);
return time;
}
double Add2(double m, double n)
{
return m + n;
}
double Add5(double a, double b, double c, double d, double e)
{
return a + b + c + d + e;
}Passing a Parameter in, or an Argument as a Constant
When you are creating a function or a method, you decide whether you want it to use one or more parameters. You indicate that a function will use a parameter as an external value to assist the function or a method in an operation. Most of the time, the function or a method uses a parameter simply to access the value of that parameter. In most of such cases, you don't change the value of the parameter. If you are using a parameter only for the value it is holding and you will not change the value of the parameter in the function or method, such a parameter is said to be passed "in". Because the function or a method doesn't change the value of the parameter, we will consider that the parameter is a constant, or we will say that the argument is passed as a constant (in C++, the "in" parameter of C# is said to be a constant, or the argument is said to be passed as a constant).
To let you indicate that you are passing a parameter "in" (or as a constant), the C# language provides a keyword named in. To apply this keyword, type it on the left side of the data type of the parameter. In the body of the function or method, you can ignore the parameter. Here is an example:
double Subtract(double a, in double b)
{
double resultDoubled = a * 2;
return resultDoubled;
}
Otherwise, in the body of the function or method, use the constant (or in) parameter anyway you want. Here is an example:
double Subtract(in double a, double b)
{
/* If you judge it necessary, you can change the value
of a regular parameter. Here is an example: */
b = 100;
return a - b;
}
The most important rule is that you cannot change the value of the in parameter in the function or method (because, as we indicated, that parameter is considered a constant); that is, in the body of the function or method, you cannot assign a value to the in parameter. Based on this, the following code will produce an error:
double Subtract(in double a, double b)
{
/* If you judge it necessary, you can change the value
of a regular parameter. Here is an example: */
b = 100;
/* You cannot change the value of an "in" parameter: */
a = 200;
return a - b;
}
When calling a function or a method that uses a constant (or in) parameter, you pass the argument exactly as done so far for regular parameters: simply provide a value for the argument. Of course, you can pass the name of a variable that holds the value of the argument. As an option, you can precede the argument with the in keyword.
Practical Learning: Passing Parameters In
using static System.Console;
PreparePayroll();
// -------------------------------------------------------
string GetFirstName()
{
WriteLine("FUN DEPARTMENT STORE");
WriteLine("=======================================================");
WriteLine("Payroll Preparation");
WriteLine("-------------------------------------------------------");
WriteLine("Enter the following pieces of information");
WriteLine("-------------------------------------------------------");
WriteLine("Employee Information");
WriteLine("-------------------------------------------------------");
Write("First Name: ");
string result = ReadLine()!;
return result;
}
string GetLastName()
{
Write("Last Name: ");
string result = ReadLine()!;
return result;
}
double GetBaseRate()
{
Write("Hourly Salary: ");
double wages = double.Parse(ReadLine()!);
return wages;
}
double GetMondayTimeWorked()
{
WriteLine("-------------------------------------------------------");
WriteLine("Time worked");
WriteLine("-------------------------------------------------------");
Write("Monday: ");
double time = double.Parse(ReadLine()!);
return time;
}
double GetTuesdayTimeWorked()
{
Write("Tuesday: ");
double time = double.Parse(ReadLine()!);
return time;
}
double GetWednesdayTimeWorked()
{
Write("Wednesday: ");
double time = double.Parse(ReadLine()!);
return time;
}
double GetThursdayTimeWorked()
{
Write("Thursday: ");
double time = double.Parse(ReadLine()!);
return time;
}
double GetFridayTimeWorked()
{
Write("Friday: ");
double time = double.Parse(ReadLine()!);
return time;
}
double Add2(in double m, in double n)
{
return m + n;
}
double Add5(in double a, in double b, in double c, in double d, in double e)
{
return a + b + c + d + e;
}
double CalculateRegularTime(double time)
{
double result = time;
if (time is > 40.00)
{
result = 40.00;
}
return result;
}
double CalculateRegularPay(double sal, double time)
{
double result = sal * time;
if (time is > 40.00)
{
result = sal * 40.00;
}
return result;
}
double CalculateOvertime(double time)
{
double result = 0.00;
if (time is > 40.00)
{
result = time - 40.00;
}
return result;
}
double CalculateOvertimePay(double sal, double time, double over)
{
double result = 0.00;
if (time is > 40.00)
{
result = sal * 1.50 * over;
}
return result;
}
void PreparePayroll()
{
string firstName = GetFirstName();
string lastName = GetLastName();
double hSalary = GetBaseRate();
double mon = GetMondayTimeWorked();
double tue = GetTuesdayTimeWorked();
double wed = GetWednesdayTimeWorked();
double thu = GetThursdayTimeWorked();
double fri = GetFridayTimeWorked();
double timeWorked = Add5(mon, tue, wed, thu, fri);
double regularTime = CalculateRegularTime(timeWorked);
double regularPay = CalculateRegularPay(hSalary, timeWorked);
double overtime = CalculateOvertime(timeWorked);
double overtimePay = CalculateOvertimePay(hSalary, timeWorked, overtime);
double weeklyPay = Add2(regularPay, overtimePay);
WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+");
WriteLine("FUN DEPARTMENT STORE");
WriteLine("=======================================================");
WriteLine("Payroll Evaluation");
WriteLine("=======================================================");
WriteLine("Employee Information");
WriteLine("-------------------------------------------------------");
WriteLine($"Full Name: {firstName} {lastName}");
WriteLine($"Hourly Salary: {hSalary:f}");
WriteLine("=======================================================");
WriteLine("Time Worked Summary");
WriteLine("--------+---------+-----------+----------+-------------");
WriteLine(" Monday | Tuesday | Wednesday | Thursday | Friday");
WriteLine("--------+---------+-----------+----------+-------------");
WriteLine($" {mon:f} | {tue:f} | {wed:f} | {thu:f} | {fri:f}");
WriteLine("========+=========+===========+==========+=============");
WriteLine(" Pay Summary");
WriteLine("-------------------------------------------------------");
WriteLine(" Time Pay");
WriteLine("-------------------------------------------------------");
WriteLine($" Regular: {regularTime:f} {regularPay:f}");
WriteLine("-------------------------------------------------------");
WriteLine($" Overtime: {overtime:f} {overtimePay:f}");
WriteLine("=======================================================");
WriteLine($" Net Pay: {weeklyPay:f}");
WriteLine("=======================================================");
}FUN DEPARTMENT STORE
=======================================================
Payroll Preparation
-------------------------------------------------------
Enter the following pieces of information
-------------------------------------------------------
Employee Information
-------------------------------------------------------
First Name: Michael
Last Name: Carlock
Hourly Salary: 28.25
-------------------------------------------------------
Time worked
-------------------------------------------------------
Monday: 7
Tuesday: 8
Wednesday: 6.5
Thursday: 8.5
Friday: 6.5
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
FUN DEPARTMENT STORE
=======================================================
Payroll Evaluation
=======================================================
Employee Information
-------------------------------------------------------
Full Name: Michael Carlock
Hourly Salary: 28.25
=======================================================
Time Worked Summary
--------+---------+-----------+----------+-------------
Monday | Tuesday | Wednesday | Thursday | Friday
--------+---------+-----------+----------+-------------
7.00 | 8.00 | 6.50 | 8.50 | 6.50
========+=========+===========+==========+=============
Pay Summary
-------------------------------------------------------
Time Pay
-------------------------------------------------------
Regular: 36.50 1031.12
-------------------------------------------------------
Overtime: 0.00 0.00
=======================================================
Net Pay: 1031.12
=======================================================
Press any key to close this window . . .A Parameter by Reference
Introduction
When calling a function or a method that takes at least one argument, if you supply an argument using its name, the compiler only makes a copy of the argument's value and passes it to the called function or a method. Although the called function or method receives the argument's value and can use it in any way it wants, it cannot (permanently) change that value. An alternative is to ask the function or method to modify the value of its parameter. If you want the called function or method to modify the value of a supplied argument and return the modified value, you can pass the argument using its reference, that is, its address. This is referred to as passing an argument by reference. The C# language provides various options.
We have already seen that you can pass an argument using the in keyword. This indicates that you are interested in a parameter for the value it is holding and you will not change the value of the argument in the body of the function or method. In some cases, you may want a function or method to change the value of a parameter. To offer a solution, the C# language provides a keyword named out. As done with the in parameter, when creating a function or a method, to apply an out-parameter, type the out keyword to the left of the data type of the parameter. Here is an example:
void ProcessWithdrawal(out double amount)
{
}
The out-parameter has some rules that go beyond those of the in keyword:
void GetWithdrawal(out double amount) { amount = 265.00; }
Before calling a function or a method that takes an out-parameter, you can first declare a variable for that parameter. Although you can, you don't have to initialize the variable. After declaring the variable, pass that variable in the placeholder of the argument. When calling the function or method, precede the argument with the out keyword. Here is an example:
using static System.Console; void GetItemName(out string name) { Write("Item Name: "); name = ReadLine()!; } string description; GetItemName(out description); WriteLine("======================================================="); WriteLine("Fun Department Store"); WriteLine(" Item Description"); WriteLine("======================================================="); WriteLine($"Item Name: {description}"); WriteLine("=======================================================");
Here is an example of running the application:
Item Name: Blue Stripped Dress ======================================================= Fun Department Store Item Description ======================================================= Item Name: Blue Stripped Dress ======================================================= Press any key to close this window . . .
Probably the most important characteristic of the out feature is that, if you change the value of the out parameter (remember that, in the body of the function or method, you must assign a value to the out-parameter), any modification made on the argument would be kept when the function or the method ends. This characteristic makes it possible for a function or a method to return many values, a feature not normally available to (regular) functions or methods. Here is an example:
using static System.Console;
void GetItemName(out string name)
{
Write("Item Name: ");
name = ReadLine()!;
}
void PrepareSale(in string desc, out double price, out double rate)
{
WriteLine("=======================================================");
WriteLine("Provide the sale preparation for {0}", desc);
WriteLine("-------------------------------------------------------");
Write("Item Price: ");
price = double.Parse(ReadLine()!);
Write("Discount Rate: ");
rate = double.Parse(ReadLine()!);
}
string description;
double cost, discount;
GetItemName(out description);
PrepareSale(in description, out cost, out discount);
WriteLine("=======================================================");
WriteLine("Fun Department Store");
WriteLine(" Item Description");
WriteLine("=======================================================");
WriteLine($"Item Name: {description}");
WriteLine($"Marked Price: {cost:c}");
WriteLine("Discount Rate: {0:p}", discount / 100.00);
WriteLine("=======================================================");
Here is an example of running the application:
Item Name: Classic Khaki Pants ======================================================= Provide the sale preparation for Classic Khaki Pants ------------------------------------------------------- Item Price: 54.75 Discount Rate: 25 ======================================================= Fun Department Store Item Description ======================================================= Item Name: Classic Khaki Pants Marked Price: $54.75 Discount Rate: 25.00% ======================================================= Press any key to close this window . . .
Practical Learning: Passing Parameters Out
using static System.Console; PreparePayroll(); // ------------------------------------------------------- void IdentifyEmployee(out string fn, out string ln, out double sal) { WriteLine("FUN DEPARTMENT STORE"); WriteLine("======================================================="); WriteLine("Payroll Preparation"); WriteLine("-------------------------------------------------------"); WriteLine("Enter the following pieces of information"); WriteLine("-------------------------------------------------------"); WriteLine("Employee Information"); WriteLine("-------------------------------------------------------"); Write("First Name: "); fn = ReadLine()!; Write("Last Name: "); ln = ReadLine()!; Write("Hourly Salary: "); sal = double.Parse(ReadLine()!); } double GetMondayTimeWorked() { WriteLine("-------------------------------------------------------"); WriteLine("Time worked"); WriteLine("-------------------------------------------------------"); Write("Monday: "); double time = double.Parse(ReadLine()!); return time; } double GetTuesdayTimeWorked() { Write("Tuesday: "); double time = double.Parse(ReadLine()!); return time; } double GetWednesdayTimeWorked() { Write("Wednesday: "); double time = double.Parse(ReadLine()!); return time; } double GetThursdayTimeWorked() { Write("Thursday: "); double time = double.Parse(ReadLine()!); return time; } double GetFridayTimeWorked() { Write("Friday: "); double time = double.Parse(ReadLine()!); return time; } double Add2(in double m, in double n) { return m + n; } double Add5(in double a, in double b, in double c, in double d, in double e) { return a + b + c + d + e; } double CalculateRegularTime(double time) { double result = time; if (time is > 40.00) { result = 40.00; } return result; } double CalculateRegularPay(double sal, double time) { double result = sal * time; if (time is > 40.00) { result = sal * 40.00; } return result; } double CalculateOvertime(double time) { double result = 0.00; if (time is > 40.00) { result = time - 40.00; } return result; } double CalculateOvertimePay(double sal, double time, double over) { double result = 0.00; if (time is > 40.00) { result = sal * 1.50 * over; } return result; } void PreparePayroll() { string firstName; string lastName; double hSalary; IdentifyEmployee(out firstName, out lastName, out hSalary); double mon = GetMondayTimeWorked(); double tue = GetTuesdayTimeWorked(); double wed = GetWednesdayTimeWorked(); double thu = GetThursdayTimeWorked(); double fri = GetFridayTimeWorked(); double timeWorked = Add5(mon, tue, wed, thu, fri); double regularTime = CalculateRegularTime(timeWorked); double regularPay = CalculateRegularPay(hSalary, timeWorked); double overtime = CalculateOvertime(timeWorked); double overtimePay = CalculateOvertimePay(hSalary, timeWorked, overtime); double weeklyPay = Add2(regularPay, overtimePay); WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+"); WriteLine("FUN DEPARTMENT STORE"); WriteLine("======================================================="); WriteLine("Payroll Evaluation"); WriteLine("======================================================="); WriteLine("Employee Information"); WriteLine("-------------------------------------------------------"); WriteLine($"Full Name: {firstName} {lastName}"); WriteLine($"Hourly Salary: {hSalary:f}"); WriteLine("======================================================="); WriteLine("Time Worked Summary"); WriteLine("--------+---------+-----------+----------+-------------"); WriteLine(" Monday | Tuesday | Wednesday | Thursday | Friday"); WriteLine("--------+---------+-----------+----------+-------------"); WriteLine($" {mon:f} | {tue:f} | {wed:f} | {thu:f} | {fri:f}"); WriteLine("========+=========+===========+==========+============="); WriteLine(" Pay Summary"); WriteLine("-------------------------------------------------------"); WriteLine(" Time Pay"); WriteLine("-------------------------------------------------------"); WriteLine($" Regular: {regularTime:f} {regularPay:f}"); WriteLine("-------------------------------------------------------"); WriteLine($" Overtime: {overtime:f} {overtimePay:f}"); WriteLine("======================================================="); WriteLine($" Net Pay: {weeklyPay:f}"); WriteLine("======================================================="); }
FUN DEPARTMENT STORE
=======================================================
Payroll Preparation
-------------------------------------------------------
Enter the following pieces of information
-------------------------------------------------------
Employee Information
-------------------------------------------------------
First Name: Catherine
Last Name: Busbey
Hourly Salary: 24.37
-------------------------------------------------------
Time worked
-------------------------------------------------------
Monday: 9.5
Tuesday: 8
Wednesday: 10.5
Thursday: 9
Friday: 8.5
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
FUN DEPARTMENT STORE
=======================================================
Payroll Evaluation
=======================================================
Employee Information
-------------------------------------------------------
Full Name: Catherine Busbey
Hourly Salary: 24.37
=======================================================
Time Worked Summary
--------+---------+-----------+----------+-------------
Monday | Tuesday | Wednesday | Thursday | Friday
--------+---------+-----------+----------+-------------
9.50 | 8.00 | 10.50 | 9.00 | 8.50
========+=========+===========+==========+=============
Pay Summary
-------------------------------------------------------
Time Pay
-------------------------------------------------------
Regular: 40.00 974.80
-------------------------------------------------------
Overtime: 5.50 201.05
=======================================================
Net Pay: 1175.85
=======================================================
Press any key to close this window . . .As mentioned earlier in our introduction, normally, when a function that takes an argument is called, the argument is accessed by its value. As an alternative, you may want to access a variable using its memory address. To make this possible, the C# language provides a keyword named ref. Besides the out keyword, the ref keyword is another way to pass an argument by reference.
When creating a function that will use a parameter by reference, precede the parameter's data type with the ref keyword. Here is an example:
void SetDeposit(ref double amount)
{
}
One of the similarities between an in and a ref parameters is that, in the body of the function or method, you can use or ignore the ref-parameter.
Before passing an argument by reference, you must first declare a variable for it. One of the differences between an out and a ref parameters is that you must initialize a ref parameter before passing it to a function or method (remember that you neither have to declare a variable for an out parameter nor have to initialize it). When calling the function or method, (you must) precede the argument's name with the ref keyword. Here is an example:
void Something()
{
double deposit = 0.00;
SetDeposit(ref deposit);
}
As mentioned for an out parameter, in the body of a function or method that uses a ref parameter, you can change the value of the parameter by assigning a new value to it. Here is an example:
void SetDeposit(ref double amount)
{
amount = 450;
}
As seen for an out-parameter, when a ref argument has changed, when the function or method ends, the ref argument keeps its new value.
You can create a function or method that uses 0, one, or more parameters as reference(s). When we studied the fact that a function or method can return a value, we saw that a function or method can return only one value because there is only one return keyword. Fortunately, the ability to use many parameters as references makes it possible for a function or method to return many values. Here is an example:
using static System.Console; void GetTimeWorked(ref double mon, ref double tue, ref double wed, ref double thu, ref double fri) { WriteLine("Type the time worked for each day"); WriteLine("-------------------------------------"); Write("Monday: "); mon = double.Parse(ReadLine()!); Write("Tuesday: "); tue = double.Parse(ReadLine()!); Write("Wednesday: "); wed = double.Parse(ReadLine()!); Write("Thursday: "); thu = double.Parse(ReadLine()!); Write("Friday: "); fri = double.Parse(ReadLine()!); } double a = 0.00, b = 0.00, c = 0.00, d = 0.00, e = 0.00; GetTimeWorked(ref a, ref b, ref c, ref d, ref e); WriteLine("==================================="); WriteLine("Fun Department Store"); WriteLine("Time Worked"); WriteLine("==================================="); WriteLine($"Monday: {a:f}"); WriteLine($"Tuesday: {b:f}"); WriteLine("Wednesday: {0:f}", c); WriteLine($"Thursday: {d:f}"); WriteLine("Friday: {0:F}", e); WriteLine("===================================");
Here is an example of running the program:
Type the time worked for each day ------------------------------------- Monday: 8.5 Tuesday: 9 Wednesday: 7.5 Thursday: 6 Friday: 9.5 Fun Department Store Time Worked =================================== Monday: 8.50 Tuesday: 9.00 Wednesday: 7.50 Thursday: 6.00 Friday: 9.50 =================================== Press any key to close this window . . .
You can create a function that receives regular parameters and parameters by reference. This creates a lot of flexibility in your applications.
Practical Learning: Passing Arguments by Reference
using static System.Console;
PreparePayroll();
// -------------------------------------------------------
void IdentifyEmployee(out string fn, out string ln, out double sal)
{
WriteLine("FUN DEPARTMENT STORE");
WriteLine("=======================================================");
WriteLine("Payroll Preparation");
WriteLine("-------------------------------------------------------");
WriteLine("Enter the following pieces of information");
WriteLine("-------------------------------------------------------");
WriteLine("Employee Information");
WriteLine("-------------------------------------------------------");
Write("First Name: ");
fn = ReadLine()!;
Write("Last Name: ");
ln = ReadLine()!;
Write("Hourly Salary: ");
sal = double.Parse(ReadLine()!);
}
void GetTimeWorked(ref double m, ref double t, ref double w, ref double h, ref double f)
{
WriteLine("-------------------------------------------------------");
WriteLine("Time worked");
WriteLine("-------------------------------------------------------");
Write("Monday: ");
m = double.Parse(ReadLine()!);
Write("Tuesday: ");
t = double.Parse(ReadLine()!);
Write("Wednesday: ");
w = double.Parse(ReadLine()!);
Write("Thursday: ");
h = double.Parse(ReadLine()!);
Write("Friday: ");
f = double.Parse(ReadLine()!);
}
double Add2(in double m, in double n)
{
return m + n;
}
double Add5(in double a, in double b, in double c, in double d, in double e)
{
return a + b + c + d + e;
}
void EvaluateSalary(double time, double sal,
ref double regTime, ref double regPay, ref double overtime, ref double overPay)
{
regTime = time;
regPay = sal * time;
overtime = 0.00;
overPay = 0.00;
if (time is > 40.00)
{
regTime = 40.00;
regPay = sal * 40.00;
overtime = time - 40.00;
overPay = sal * 1.50 * overtime;
}
}
void PreparePayroll()
{
string firstName;
string lastName;
double hSalary;
double mon = 0.00;
double tue = 0.00;
double wed = 0.00;
double thu = 0.00;
double fri = 0.00;
double regularTime = 0.00;
double regularPay = 0.00;
double overtime = 0.00;
double overtimePay = 0.00;
IdentifyEmployee(out firstName, out lastName, out hSalary);
GetTimeWorked(ref mon, ref tue, ref wed, ref thu, ref fri);
double timeWorked = Add5(mon, tue, wed, thu, fri);
EvaluateSalary(timeWorked, hSalary,
ref regularTime, ref regularPay, ref overtime, ref overtimePay);
double weeklyPay = Add2(regularPay, overtimePay);
WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+");
WriteLine("FUN DEPARTMENT STORE");
WriteLine("=======================================================");
WriteLine("Payroll Evaluation");
WriteLine("=======================================================");
WriteLine("Employee Information");
WriteLine("-------------------------------------------------------");
WriteLine($"Full Name: {firstName} {lastName}");
WriteLine($"Hourly Salary: {hSalary:f}");
WriteLine("=======================================================");
WriteLine("Time Worked Summary");
WriteLine("--------+---------+-----------+----------+-------------");
WriteLine(" Monday | Tuesday | Wednesday | Thursday | Friday");
WriteLine("--------+---------+-----------+----------+-------------");
WriteLine($" {mon:f} | {tue:f} | {wed:f} | {thu:f} | {fri:f}");
WriteLine("========+=========+===========+==========+=============");
WriteLine(" Pay Summary");
WriteLine("-------------------------------------------------------");
WriteLine(" Time Pay");
WriteLine("-------------------------------------------------------");
WriteLine($" Regular: {regularTime:f} {regularPay:f}");
WriteLine("-------------------------------------------------------");
WriteLine($" Overtime: {overtime:f} {overtimePay:f}");
WriteLine("=======================================================");
WriteLine($" Net Pay: {weeklyPay:f}");
WriteLine("=======================================================");
}FUN DEPARTMENT STORE
=======================================================
Payroll Preparation
-------------------------------------------------------
Enter the following pieces of information
-------------------------------------------------------
Employee Information
-------------------------------------------------------
First Name: Andrew
Last Name: Sanders
Hourly Salary: 26.97
-------------------------------------------------------
Time worked
-------------------------------------------------------
Monday: 9
Tuesday: 10.50
Wednesday: 7
Thursday: 9.50
Friday: 8.50
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
FUN DEPARTMENT STORE
=======================================================
Payroll Evaluation
=======================================================
Employee Information
-------------------------------------------------------
Full Name: Andrew Sanders
Hourly Salary: 26.97
=======================================================
Time Worked Summary
--------+---------+-----------+----------+-------------
Monday | Tuesday | Wednesday | Thursday | Friday
--------+---------+-----------+----------+-------------
9.00 | 10.50 | 7.00 | 9.50 | 8.50
========+=========+===========+==========+=============
Pay Summary
-------------------------------------------------------
Time Pay
-------------------------------------------------------
Regular: 40.00 1078.80
-------------------------------------------------------
Overtime: 4.50 182.05
=======================================================
Net Pay: 1260.85
=======================================================
Press any key to close this window . . .Referenced Tuples
Passing a Constant Tuple
As you may know already, you can create a function or a method that uses a tuple as parameter. Here are two examples:
using static System.Console; (int memNbr, string name, string category, int fee) person = (938_405, "Matthew Groeder", "Adult", 25); DisplayMemberInfo(person); UpdateMemberInfo(person); void DisplayMemberInfo((int memNbr, string name, string category, int fee) member) { WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+"); WriteLine("Club Membership"); WriteLine("================================="); WriteLine("Member Information"); WriteLine("---------------------------------"); WriteLine($"Membership #: {member.memNbr}"); WriteLine($"Member Name: {member.name}"); WriteLine($"Membership Type: {member.category}"); WriteLine($"Membership Fee: ${member.fee}"); WriteLine("================================="); } void UpdateMemberInfo((int memNbr, string name, string category, int fee) member) { member.memNbr = 493_749; member.name = "James Quick"; member.category = "Teen"; member.fee = 10; WriteLine("Club Membership"); WriteLine("================================="); WriteLine("Member Information"); WriteLine("---------------------------------"); WriteLine($"Membership #: {member.memNbr}"); WriteLine($"Member Name: {member.name}"); WriteLine($"Membership Type: {member.category}"); WriteLine($"Membership Fee: ${member.fee}"); WriteLine("================================="); }
This would produce:
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ Club Membership ================================= Member Information --------------------------------- Membership #: 938405 Member Name: Matthew Groeder Membership Type: Adult Membership Fee: $25 ================================= Club Membership ================================= Member Information --------------------------------- Membership #: 493749 Member Name: James Quick Membership Type: Teen Membership Fee: $10 ================================= Press any key to close this window . . .
Notice that the first function doesn't change the values of the tuple but the second function does. If you are creating a function that uses a tuple as parameter and the function doesn't change the values of the tuple, you can indicate that the parameter is a constant. As seen with the values of primitive types, you can precede the parameter with in. This can be done as follows:
using static System.Console;
(int memNbr, string name, string category, int fee) person = (938_405, "Matthew Groeder", "Adult", 25);
DisplayMemberInfo(person);
void DisplayMemberInfo(in (int memNbr, string name, string category, int fee) member)
{
WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+");
WriteLine("Club Membership");
WriteLine("=================================");
WriteLine("Member Information");
WriteLine("---------------------------------");
WriteLine($"Membership #: {member.memNbr}");
WriteLine($"Member Name: {member.name}");
WriteLine($"Membership Type: {member.category}");
WriteLine($"Membership Fee: ${member.fee}");
WriteLine("=================================");
}
As seen with values of primitive types, if you specify that a tuple parameter is treated as a constant, in the body of the function, you cannot modify any item of the tuple; for example, you cannot assign new values to the items of the tuple. As a result, the following code would not compile:
void UpdateMemberInfo(in (int memNbr, string name, string category, int fee) member) { member.memNbr = 493_749; member.name = "James Quick"; member.category = "Teen"; member.fee = 10; WriteLine("================================="); WriteLine("Club Membership"); WriteLine("================================="); WriteLine("Member Information"); WriteLine("---------------------------------"); WriteLine($"Membership #: {member.memNbr}"); WriteLine($"Member Name: {member.name}"); WriteLine($"Membership Type: {member.category}"); WriteLine($"Membership Fee: ${member.fee}"); WriteLine("================================="); }
Practical Learning: Introducing Referenced Tuples
using static System.Console;
/* We are calling a function that returns a triple-item tuple,
* and we are assigning the returned tuple to a tuple variable. */
(double principal, double interestRate, double periods) compInt = GetValues();
double per = DivideBy100(compInt.periods);
/* We are calling a function that returns a triple-item tuple.
* We are assigning the returned tuple to a tuple variable. */
(double principal, double interestRate, double per) periodics = (compInt.principal, compInt.interestRate, per);
/* We are calling a function that takes a triple-item tuple as argument
* and returns a floating-point value.
* We are assigning the returned values to a double-precision variable. */
double futureValue = CalculateFutureValue(periodics);
/* We creating a double-item tuple for a future value and a principal.
* We are declaring a double-item tuple variable for a future value
* and a principal, and we are assigning the double-item tuple to it.
* (The reason we are creating a double-item tuple is that we want
* to pass it to a function that takes a double-item tuple as argument.) */
(double future, double principal) futureAndPrincipal = (futureValue, compInt.principal);
/* We are calling a function that returns a double-item tuple,
* We are assigning the returned value to a floating-point variable. */
double interestEarned = Subtract(futureAndPrincipal);
// We are calling a function that takes a triple-item tuple as argument.
Display(compInt);
(double a, double b, double c) GetValues()
{
double principal = 0d, interestRate = 0d, periods = 0d;
try
{
Write("Principal: ");
principal = double.Parse(ReadLine()!);
}
catch (FormatException fe)
{
WriteLine("The value for the principal is not valid. Please report the error as follows: " + fe.Message);
}
try
{
Write("Interest Rate: ");
interestRate = Convert.ToDouble(ReadLine()!);
}
catch (FormatException fe)
{
WriteLine("The value for the interest rate is not valid. Please report the error as follows: " + fe.Message);
}
try
{
Write("Periods: ");
periods = Convert.ToDouble(ReadLine()!);
}
catch (FormatException fe)
{
WriteLine("The value for the period is not valid. Please report the error as follows: " + fe.Message);
}
return (principal, interestRate, periods);
}
double DivideBy100(in double number)
{
return number / 100;
}
void Display(in (double principal, double interestRate, double periods) compInt)
{
WriteLine("===========================");
WriteLine("Compound Interest");
WriteLine("===========================");
WriteLine("Principal: {0:f}", compInt.principal);
WriteLine("Interest Rate: {0:f}%", compInt.interestRate);
WriteLine("Periods: {0} years", compInt.periods);
WriteLine("---------------------------");
WriteLine("Future Value: {0:f}", futureValue);
WriteLine("Interest Earned: {0:f}", interestEarned);
WriteLine("===========================");
}
double Subtract(in (double left, double right) values)
{
return values.left - values.right;
}
double CalculateFutureValue(in (double princ, double iRate, double per) values)
{
return futureValue = values.princ * Math.Pow((1.00 + (values.iRate / 1)), 1 * values.per);
}Principal: 6885.85 Interest Rate: 8.725 Periods: 5 =========================== Compound Interest =========================== Principal: 6885.85 Interest Rate: 8.72% Periods: 5 years --------------------------- Future Value: 7715.29 Interest Earned: 829.44 =========================== Press any key to close this window . . .
Passing a Tuple Out
Consider the following code:
We already know that the tuple feature in C# solves the problem of returning many values from a function or method. Still, if you want, you can create a function or method that uses a tuple as parameter. This would make the function or method return many values. In our introduction to references, we saw that if you create a parameter as a reference, when its function or method ends, that parameter would come back with a new value. We saw that one way to do this is to create a parameter as an out one. This feature is also available for tuples.
To create a tuple as an out parameter, in the parentheses of the function or method, add the tuple but precede it with the out keyword. In the body of the function or method, create any behavior you want. Before the function or method ends, assign the desired value to the tuple parameter. When calling the function or method, pass a regular tuple to it but, of course, the tuple must have the same number and types of items as those that the function or method is using.
Practical Learning: Passing a Tuple Out
using static System.Console; /* We are calling a function that returns a triple-item tuple, * and we are assigning the returned tuple to a tuple variable. */ (double principal, double interestRate, double periods) compInt; GetValues(out compInt); double per = DivideBy100(compInt.periods); /* We are calling a function that returns a triple-item tuple. * We are assigning the returned tuple to a tuple variable. */ (double principal, double interestRate, double per) periodics = (compInt.principal, compInt.interestRate, per); /* We are calling a function that takes a triple-item tuple as argument * and returns a floating-point value. * We are assigning the returned values to a double-precision variable. */ double futureValue = CalculateFutureValue(periodics); /* We creating a double-item tuple for a future value and a principal. * We are declaring a double-item tuple variable for a future value * and a principal, and we are assigning the double-item tuple to it. * (The reason we are creating a double-item tuple is that we want * to pass it to a function that takes a double-item tuple as argument.) */ (double future, double principal) futureAndPrincipal = (futureValue, compInt.principal); /* We are calling a function that returns a double-item tuple, * We are assigning the returned value to a floating-point variable. */ double interestEarned = Subtract(futureAndPrincipal); // We are calling a function that takes a triple-item tuple as argument. Display(compInt); void GetValues(out (double a, double b, double c) items) { double principal = 0d, interestRate = 0d, periods = 0d; . . . No Change items = (principal, interestRate, periods); } double DivideBy100(in double number) { return number / 100; } void Display(in (double principal, double interestRate, double periods) compInt) { WriteLine("==========================="); WriteLine("Compound Interest"); WriteLine("==========================="); WriteLine("Principal: {0:f}", compInt.principal); WriteLine("Interest Rate: {0:f}%", compInt.interestRate); WriteLine("Periods: {0} years", compInt.periods); WriteLine("---------------------------"); WriteLine("Future Value: {0:f}", futureValue); WriteLine("Interest Earned: {0:f}", interestEarned); WriteLine("==========================="); } double Subtract(in (double left, double right) values) { return values.left - values.right; } double CalculateFutureValue(in (double princ, double iRate, double per) values) { return futureValue = values.princ * Math.Pow((1.00 + (values.iRate / 1)), 1 * values.per); }
Principal: 5675.35 Interest Rate: 6.225 Periods: 4 =========================== Compound Interest =========================== Principal: 5675.35 Interest Rate: 6.22% Periods: 4 years --------------------------- Future Value: 6142.51 Interest Earned: 467.16 =========================== Press any key to close this window . . .
Passing a Tuple by Reference
As seen with primitive types, another way to create a parameter is as a reference. This feature is also available to tuples. To proceed, when creating a function or method, in its parentheses, create a tuple. Precede that tuple with the ref keyword. In the body of the function or method, you can use or ignore the parameter (remember that, if you create a parameter as out, you must initialize it in the body of the function or method). Before calling the function or method, you must declare a tuple variable and you must initialize it. The tuple must have the same syntax as the parameter of the function or method. When calling the function or method, you can pass the tuple variable you had declared. You must precede the argument with the ref keyword. As mentioned already, when the function or method is called, the argument would carry a new value if the parameter got a new value in the body of the function or method.
Practical Learning: Passing a Tuple Out
using static System.Console; (double principal, double interestRate, double periods) compInt = (0, 0, 0); GetValues(ref compInt); double per = DivideBy100(compInt.periods); (double principal, double interestRate, double per) periodics = (compInt.principal, compInt.interestRate, per); double futureValue = CalculateFutureValue(periodics); (double future, double principal) futureAndPrincipal = (futureValue, compInt.principal); double interestEarned = Subtract(futureAndPrincipal); Display(compInt); void GetValues(ref (double a, double b, double c) items) { double principal = 0d, interestRate = 0d, periods = 0d; try { Write("Principal: "); principal = double.Parse(ReadLine()!); } catch (FormatException fe) { WriteLine("The value for the principal is not valid. Please report the error as follows: " + fe.Message); } try { Write("Interest Rate: "); interestRate = Convert.ToDouble(ReadLine()!); } catch (FormatException fe) { WriteLine("The value for the interest rate is not valid. Please report the error as follows: " + fe.Message); } try { Write("Periods: "); periods = Convert.ToDouble(ReadLine()!); } catch (FormatException fe) { WriteLine("The value for the period is not valid. Please report the error as follows: " + fe.Message); } items = (principal, interestRate, periods); } double DivideBy100(in double number) { return number / 100; } void Display(in (double principal, double interestRate, double periods) compInt) { WriteLine("==========================="); WriteLine("Compound Interest"); WriteLine("==========================="); WriteLine("Principal: {0:f}", compInt.principal); WriteLine("Interest Rate: {0:f}%", compInt.interestRate); WriteLine("Periods: {0} years", compInt.periods); WriteLine("---------------------------"); WriteLine("Future Value: {0:f}", futureValue); WriteLine("Interest Earned: {0:f}", interestEarned); WriteLine("==========================="); } double Subtract(in (double left, double right) values) { return values.left - values.right; } double CalculateFutureValue(in (double princ, double iRate, double per) values) { return futureValue = values.princ * Math.Pow((1.00 + (values.iRate / 1)), 1 * values.per); }
Principal: 12455.55 Interest Rate: 5.555 Periods: 5 =========================== Compound Interest =========================== Principal: 12455.55 Interest Rate: 5.55% Periods: 5 years --------------------------- Future Value: 13683.32 Interest Earned: 1227.77 =========================== Press any key to close this window . . .
|
|
|||
| Previous | Copyright © 2011-2025, FunctionX | Friday 19 January 2024 | Next |
|
|
|||