﻿ Lesson 10: The Parameters of a Function

Introduction to Parameters of a Function

Overview

To perform its action(s), a function may need some values. If you are creating a function that will need values, you must indicate it. To do this, when creating a function, in its parentheses, enter a data type and a name. Here is an example:

```void ProtectFromBadWeather(string typeOfRoof)
{
}```

The combination of data type and name that you provide to a function is called a parameter. In the body of the function, you can use the parameter or ignore it completely. When using the parameter, you can involve it in any operation that is appropriate for its type. For example, if it is a number, you can involve it in any algebraic operation. If it is a string or any other type, use it anyway you want. Here is an example:

```using static System.Console;

void ProtectFromBadWeather(string typeOfRoof)
{
Write("Roof Type: ");
WriteLine(typeOfRoof);
}```

In the body of the function, you can also ignore the parameter. This means that, in the body of the function, you can decide not to use a parameter.

Practical Learning: Introducing Parameters

• Start Microsoft Visual Studio and create a new Console App named TaxPreparation07 that supports .NET 6.0 (Long-Term Support)

Calling a Function that Uses a Parameter

When calling a function that uses a parameter, you must provide a value for the parameter. The value provided in the parentheses of the function is called an argument. The action of providing a value in the parentheses of the function is referred to as passing an argument to the function.

There are various ways you can pass an argument to a function. If you have the value you want to use, provide it in the parentheses of the function. Here is an example:

```using static System.Console;

string PropertyType;
int    Bedrooms;
double MarketValue;

void ProtectFromBadWeather(string typeOfRoof)
{
Write("Roof Type: ");
WriteLine(typeOfRoof);
}

void ShowCharacteristics()
{
WriteLine("=//= Altair Realtors =//=");
WriteLine("Properties Inventory");
Write("Property Type: ");
WriteLine(PropertyType);

ProtectFromBadWeather("Asphalt Shingles");

Write("Bedrooms: ");
WriteLine(Bedrooms);
Write("Market Value: ");
WriteLine(MarketValue);
}```

If the value is stored in a variable, you can pass the name of the variable to the function. Here is an example:

```using static System.Console;

string PropertyType;
int    Bedrooms;
double MarketValue;

void ProtectFromBadWeather(string typeOfRoof)
{
Write("Roof Type: ");
WriteLine(typeOfRoof);
}

void ShowCharacteristics()
{
string roofMaterial = "Asphalt Shingles";

WriteLine("=//= Altair Realtors =//=");
WriteLine("Properties Inventory");
Write("Property Type: ");
WriteLine(PropertyType);

ProtectFromBadWeather(roofMaterial);

Write("Bedrooms: ");
WriteLine(Bedrooms);
Write("Market Value: ");
WriteLine(MarketValue);
}```

Practical Learning: Introducing Parameters

1. Change the document as follows:
```using static System.Console;

double first3000, next2000, next5000, over10000;

double EvaluateTaxLiability(double grossSalary)
{
/* https://www.dor.ms.gov/individual/tax-rates
* Mississippi has a graduated tax rate.
* There is no tax schedule for Mississippi income taxes.
* The graduated income tax rate is:
* 0% on the first \$3,000 of taxable income.​
* 3% on the next  \$2,000 of taxable income.​
* 4% on the next  \$5,000 of taxable income.
* 5% on all taxable income over \$10,000.   */

if((grossSalary > 0) && (grossSalary <= 3_000))
{
first3000 = 0.00;
next2000  = 0.00;
next5000  = 0.00;
over10000 = 0.00;
}
else if((grossSalary > 3_000) && (grossSalary <= 5_000))
{
first3000 = 0.00;
next2000 = (grossSalary - 3_000) * 3 / 100;
next5000 = 0.00;
over10000 = 0.00;
}
else if((grossSalary > 5_000) && (grossSalary <= 10_000))
{
first3000 = 0.00;
next2000 = 2_000 * 3 / 100;
next5000 = (grossSalary - 5_000) * 4 / 100;
over10000 = 0.00;
}
else // if(grossSalary > 10_000)
{
first3000 = 0.00;
next2000 = 2_000 * 3 / 100;
next5000 = 5_000 * 4 / 100;
over10000 = (grossSalary - 10_000) * 5 / 100;
}

return first3000 + next2000 + next5000 + over10000;
}

double CalculateSalary(double grossSalary)
{
return grossSalary - EvaluateTaxLiability(grossSalary);
}

WriteLine("============================================");
WriteLine(" - Amazing DeltaX - State Income Tax -");
WriteLine("--------------------------------------------");
WriteLine("          -=- Mississippi -=-");
WriteLine("============================================");

WriteLine("Enter the information to prepare the taxes");
Write("Gross Salary:  ");
double grossSalary = double.Parse(ReadLine());

double taxAmount = EvaluateTaxLiability(grossSalary);

WriteLine("============================================");
WriteLine(" - Amazing DeltaX - State Income Tax -");
WriteLine("--------------------------------------------");
WriteLine("          -=- Mississippi -=-");
WriteLine("============================================");
WriteLine(\$"Gross Salary:  {grossSalary:f}");
WriteLine("--------------------------------------------");
WriteLine(\$"First \$3000:   {first3000:f}");
WriteLine(\$"Next  \$2000:   {next2000:f}");
WriteLine(\$"Next  \$5000:   {next5000:f}");
WriteLine(\$"Over  \$10,000: {over10000:f}");
WriteLine("--------------------------------------------");
WriteLine(\$"Tax Amount:    {taxAmount:f}");
WriteLine(\$"Net Pay:       {CalculateSalary(grossSalary):f}");
WriteLine("============================================");```
2. To execute, on the main menu, click Debug -> Start Without Debugging
3. When requested, for the Gross Salary, type 2249.65 and press Enter:
```============================================
- Amazing DeltaX - State Income Tax -
--------------------------------------------
-=- Mississippi -=-
============================================
Enter the information to prepare the taxes
Gross Salary:  2249.65
============================================
- Amazing DeltaX - State Income Tax -
--------------------------------------------
-=- Mississippi -=-
============================================
Gross Salary:  2249.65
--------------------------------------------
First \$3000:   0.00
Next  \$2000:   0.00
Next  \$5000:   0.00
Over  \$10,000: 0.00
--------------------------------------------
Tax Amount:    0.00
Net Pay:       2249.65
============================================

Press any key to close this window . . .```
4. Press Enter to close the window and return to your programming environment
5. To execute, press Ctrl + F5
6. For the Gross Salary, type 4264.85 and press Enter
```============================================
- Amazing DeltaX - State Income Tax -
--------------------------------------------
-=- Mississippi -=-
============================================
Enter the information to prepare the taxes
Gross Salary:  4264.85
============================================
- Amazing DeltaX - State Income Tax -
--------------------------------------------
-=- Mississippi -=-
============================================
Gross Salary:  4264.85
--------------------------------------------
First \$3000:   0.00
Next  \$2000:   37.95
Next  \$5000:   0.00
Over  \$10,000: 0.00
--------------------------------------------
Tax Amount:    37.95
Net Pay:       4226.90
============================================

Press any key to close this window . . .```
7. Press G to close the window and return to your programming environment
8. To execute again12, on the main menu, click Debug -> Start Without Debugging
9. For the Gross Salary, type 6288.95 and press Enter:
```============================================
- Amazing DeltaX - State Income Tax -
--------------------------------------------
-=- Mississippi -=-
============================================
Enter the information to prepare the taxes
Gross Salary:  6288.95
============================================
- Amazing DeltaX - State Income Tax -
--------------------------------------------
-=- Mississippi -=-
============================================
Gross Salary:  6288.95
--------------------------------------------
First \$3000:   0.00
Next  \$2000:   60.00
Next  \$5000:   51.56
Over  \$10,000: 0.00
--------------------------------------------
Tax Amount:    111.56
Net Pay:       6177.39
============================================

Press any key to close this window . . .```
10. Press B to close the window and return to your programming environment
11. To execute the project again, press Ctrl + F5
12. For the Gross Salary, type 12464.85 and press Enter
```============================================
- Amazing DeltaX - State Income Tax -
--------------------------------------------
-=- Mississippi -=-
============================================
Enter the information to prepare the taxes
Gross Salary:  12464.85
============================================
- Amazing DeltaX - State Income Tax -
--------------------------------------------
-=- Mississippi -=-
============================================
Gross Salary:  12464.85
--------------------------------------------
First \$3000:   0.00
Next  \$2000:   60.00
Next  \$5000:   200.00
Over  \$10,000: 123.24
--------------------------------------------
Tax Amount:    383.24
Net Pay:       12081.61
============================================

Press any key to close this window . . .```
13. Press H to close the window and return to your programming environment
14. To reduce the code of the functions, change them as follows:
```using static System.Console;

double EvaluateTaxLiability(double grossSalary)
{
/* https://www.dor.ms.gov/individual/tax-rates
* Mississippi has a graduated tax rate.
* There is no tax schedule for Mississippi income taxes.
* The graduated income tax rate is:
* 0% on the first \$3,000 of taxable income.​
* 3% on the next  \$2,000 of taxable income.​
* 4% on the next  \$5,000 of taxable income.
* 5% on all taxable income over \$10,000.   */

if((grossSalary > 0) && (grossSalary <= 3_000))
return 0.00;
else if((grossSalary > 3_000) && (grossSalary <= 5_000))
return (grossSalary - 3_000) * 3 / 100;
else if((grossSalary > 5_000) && (grossSalary <= 10_000))
return (2_000 * 3 / 100) + ((grossSalary - 5_000) * 4 / 100);
else // if(grossSalary > 10_000)

return (2_000 * 3 / 100) + (5_000 * 4 / 100) + ((grossSalary - 10_000) * 5 / 100);
}

double CalculateSalary(double grossSalary) => grossSalary - EvaluateTaxLiability(grossSalary);

WriteLine("============================================");
WriteLine(" - Amazing DeltaX - State Income Tax -");
WriteLine("--------------------------------------------");
WriteLine("          -=- Mississippi -=-");
WriteLine("============================================");

WriteLine("Enter the information to prepare the taxes");
Write("Gross Salary:  ");
double grossSalary = double.Parse(ReadLine());

WriteLine("============================================");
WriteLine(" - Amazing DeltaX - State Income Tax -");
WriteLine("--------------------------------------------");
WriteLine("          -=- Mississippi -=-");
WriteLine("============================================");
WriteLine(\$"Gross Salary:  {grossSalary:f}");
WriteLine("--------------------------------------------");
WriteLine(\$"Tax Amount:    {EvaluateTaxLiability(grossSalary):f}");
WriteLine(\$"Net Pay:       {CalculateSalary(grossSalary):f}");
WriteLine("============================================");```
15. To execute, press Ctrl + F5
16. For the Gross Salary, type 7495.85 and press Enter:
```============================================
- Amazing DeltaX - State Income Tax -
--------------------------------------------
-=- Mississippi -=-
============================================
Enter the information to prepare the taxes
Gross Salary:  7495.85
============================================
- Amazing DeltaX - State Income Tax -
--------------------------------------------
-=- Mississippi -=-
============================================
Gross Salary:  7495.85
--------------------------------------------
Tax Amount:    159.83
Net Pay:       7336.02
============================================
Press any key to close this window . . .```
17. Press N to close the window and return to your programming environment
18. To start a new project, on the main menu of Microsoft Visual Studio, click File -> New -> Project...
19. Make sure C# is set and Console Application is selected. Click Next
20. Change the project Name to TaxPreparation08 and accept or change the project Location
21. Click Next
22. Make sure the Target Framework combo box is displaying .NET 5.0 (Current).
Click Finish
23. Change the document as follows:
```using static System.Console;

void Announce()
{
}

string GetFilingStatus()
{
return;
}

double GetGrossSalary()
{
return 0.00;
}

double taxAmount = 0.00;
double net_pay   = 0.00;```

Boolean Values and Functions

A Boolean Parameter

Like parameters of the other types, you can create a function that uses a parameter of bool type. Here is an example:

```void CalculatePayroll(bool fullTime)
{

}```

In the body of the function, the parameter is treated as holding a true or false value. When calling the function, pass such a value or a variable that holds that value. Here is an example:

```void CalculatePayroll(bool fullTime)
{

}

void ValidateEmploymentStatus()
{
CalculatePayroll(false);
}```

Returning a Boolean Value

You can create a function or a function that produces a Boolean value. To do that, when creating the function, on the left side of the name of the function, type bool. In the body of the function, perform the desired operation. Before the closing curly bracket, type return followed by a Boolean value or expression. Here is an example:

```bool Validate()
{
bool a = true;

return a;
}```

A Function With Many Parameters

Introduction

A function can use many parameters, as many as you judge them necessary. When creating the function, in its parentheses, provide each parameter by its data type and a name. The parameters are separated by commas. The parameters can be of the same type. Here is an example:

```void ShowTimeWorked(string startTime, string endTime)
{

}```

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

```void ShowTimeWorked(string startTime, int timeWorked, string endTime)
{

}```

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

Practical Learning: Creating Functions With Many Parameters

• Change the document as follows:
```using static System.Console;

void Announce()
{
}

string GetFilingStatus()
{
return ;
}

double GetGrossSalary()
{
return 0.00;
}

double CalculateTaxAmount(string status, double salary)
{
return 0.00;
}

double CalculateNetPay(double salary, double tax)
{
return salary - tax;
}

double taxAmount = 0.00;
double net_pay   = 0.00;```

Calling a Function of Many Parameters

When calling a function that uses many parameters, you must provide a value for each parameter in the order the parameters appear in the parentheses.

### New Convention:

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

`return-type function-name(parameter(s));`

This means that we are referring to the function function-name that uses the parameter(s) specified. We will also provide (or reviewg) the return type of the function.

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

Practical Learning: Calling a Function of Many Parameters

1. Change the document as follows:
```using static System.Console;

void Announce()
{
WriteLine("=========================================================");
WriteLine(" - Amazing DeltaX - State Income Tax -");
WriteLine("---------------------------------------------------------");
WriteLine("          -=- Georgia -=-");
WriteLine("=========================================================");
}

string GetFilingStatus()
{
WriteLine("Filing Status");
WriteLine("i - Single");
WriteLine("s - Married Filing Separate");
WriteLine("j - Married Filing Joint or Head of Household");
Write("Enter Filing Status: ");
string answer = ReadLine();

if ((answer == "s") || (answer == "S"))
return "Married Filing Separate";
else if ((answer == "j") || (answer == "J"))
return "Married Filing Joint or Head of Household";
else // if ((answer == "i") || (answer == "I"))
return "Single";
}

double GetGrossSalary()
{
Write("Gross Salary:        ");
double grossSalary = double.Parse(ReadLine());

return grossSalary;
}

double CalculateTaxAmount(string status, double salary)
{
double taxRate, addedAmount;

// Georgia
if (status == "Married Filing Joint or Head of Household")
{
if (salary is >= 10_000)
{
addedAmount = 340;
taxRate = 5.75;
}
else if (salary is >= 7_000)
{
addedAmount = 190;
taxRate = 5.00;
}
else if (salary is >= 5_000)
{
addedAmount = 110;
taxRate = 4.00;
}
else if (salary is >= 3_000)
{
addedAmount = 50;
taxRate = 3.00;
}
else if (salary is >= 1_000)
{
addedAmount = 10;
taxRate = 2.00;
}
else // if salary < 1_000:)
{
addedAmount = 0;
taxRate = 1.00;
}
}
else if (status == "Married Filing Separate")
{
if (salary is >= 5_000)
{
addedAmount = 170;
taxRate = 5.75;
}
else if (salary is >= 3_500)
{
addedAmount = 95;
taxRate = 5.00;
}
else if (salary is >= 2_500)
{
addedAmount = 55;
taxRate = 4.00;
}
else if (salary is >= 1_500)
{
addedAmount = 25;
taxRate = 3.00;
}
else if (salary is >= 500)
{
addedAmount = 5;
taxRate = 2.00;
}
else // if( salary < 1_000)
{
addedAmount = 0;
taxRate = 1.00;
}
}
else // "Single";
{
if (salary is >= 7_000)
{
addedAmount = 230;
taxRate = 5.75;
}
else if (salary is >= 5_250)
{
addedAmount = 143;
taxRate = 5.00;
}
else if (salary is >= 3_750)
{
addedAmount = 83;
taxRate = 4.00;
}
else if (salary is >= 2_250)
{
addedAmount = 38;
taxRate = 3.00;
}
else if (salary is >= 750)
{
addedAmount = 8;
taxRate = 2.00;
}
else // if salary < 750:)
{
addedAmount = 0;
taxRate = 1.00;
}
}

return addedAmount + (salary * taxRate / 100.00);
}

double CalculateNetPay(double salary, double tax)
{
return salary - tax;
}

Announce();

WriteLine("Enter the information for tax preparation");
string filingStatus = GetFilingStatus();
double grossSalary = GetGrossSalary();

double taxAmount = CalculateTaxAmount(filingStatus, grossSalary);
double net_pay = CalculateNetPay(grossSalary, taxAmount);

Announce();

WriteLine(\$"Gross Salary:  {grossSalary:f}");
WriteLine(\$"Filing Status: {filingStatus}");
WriteLine("---------------------------------------------------------");
WriteLine(\$"Tax Amount:    {taxAmount:f}");
WriteLine(\$"Net Pay:       {net_pay:f}");
WriteLine("=========================================================");```
2. To execute, on the main menu, click Debug -> Start Without Debugging
3. For the Filing Status, type J and press Enter
4. For the Gross Salary, type 1688.85 and press Enter:
```=========================================================
- Amazing DeltaX - State Income Tax -
---------------------------------------------------------
-=- Georgia -=-
=========================================================
Enter the information for tax preparation
Filing Status
i - Single
s - Married Filing Separate
j - Married Filing Joint or Head of Household
Enter Filing Status: J
Gross Salary:        1688.85
=========================================================
- Amazing DeltaX - State Income Tax -
---------------------------------------------------------
-=- Georgia -=-
=========================================================
Gross Salary:  1688.85
Filing Status: Married Filing Joint or Head of Household
---------------------------------------------------------
Tax Amount:    43.78
Net Pay:       1645.07
=========================================================
Press any key to close this window . . .```
5. Press T to close the window and return to your programming environment

Accessing a Parameter by Name

If you call a function 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.

Practical Learning: Accessing a Parameter by Name

1. To change the functions in one-line code, change them as tollows:
```using static System.Console;

void Announce()
{
. . .
}

string GetFilingStatus()
{
. . .
}

double GetGrossSalary()
{
. . .
}

double CalculateTaxAmount(string status, double salary)
{
. . .
}

double CalculateNetPay(double salary, double tax)
{
return salary - tax;
}

Announce();

WriteLine("Enter the information for tax preparation");
string filingStatus = GetFilingStatus();
double grossSalary  = GetGrossSalary();

double taxAmount = CalculateTaxAmount(salary: grossSalary, status: filingStatus);
double net_pay   = CalculateNetPay(tax: taxAmount, salary: grossSalary);

Announce();

WriteLine(\$"Gross Salary:  {grossSalary:f}");
WriteLine(\$"Filing Status: {filingStatus}");
WriteLine("---------------------------------------------------------");
WriteLine(\$"Tax Amount:    {taxAmount:f}");
WriteLine(\$"Net Pay:       {net_pay:f}");
WriteLine("=========================================================");```
2. To execute, on the main menu, click Debug -> Start Without Debugging
3. For the Filing Status, type S and press Enter
4. For the Gross Salary, type 1688.85 and press Enter:
```=========================================================
- Amazing DeltaX - State Income Tax -
---------------------------------------------------------
-=- Georgia -=-
=========================================================
Enter the information for tax preparation
Filing Status
i - Single
s - Married Filing Separate
j - Married Filing Joint or Head of Household
Enter Filing Status: S
Gross Salary:        1688.85
=========================================================
- Amazing DeltaX - State Income Tax -
---------------------------------------------------------
-=- Georgia -=-
=========================================================
Gross Salary:  1688.85
Filing Status: Married Filing Separate
---------------------------------------------------------
Tax Amount:    75.67
Net Pay:       1613.18
=========================================================
Press any key to close this window . . .```
5. Press N to close the window and return to your programming environment

A Parameter With an Optional Value

Introduction

Consider the following code:

```double originalPrice;

double CalculatePriceAfterDiscount(double discountRate)
{
return originalPrice - (originalPrice * discountRate / 100);
}```

We have learned that if a function uses a parameter, when you call that function, you must provide a value for the argument. Here is an example:

```using static System.Console;

double originalPrice;

double CalculatePriceAfterDiscount(double discountRate)
{
return originalPrice - (originalPrice * discountRate / 100);
}

double discountRate = 20.00; // 20%
originalPrice   = 198.75;

double priceAfterDiscount = CalculatePriceAfterDiscount(discountRate);

WriteLine("Fun Department Store");
WriteLine("===================================");
WriteLine(\$"Orignial Price:  {originalPrice}");
WriteLine(\$"Discount Rate:   {discountRate}%");
WriteLine("-----------------------------------");
WriteLine(\$"Marked Price:    {priceAfterDiscount:F}");
WriteLine("===================================");```

This would produce:

```Fun Department Store
===================================
Orignial Price:  198.75
Discount Rate:   20%
-----------------------------------
Marked Price:    159.00
===================================

Press any key to close this window . . .```

If you have a function 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 function, after the name of the parameter, assign the default value to it. Here is an example:

```public double OriginalPrice;

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

When calling the function, 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:

```using static System.Console;

double originalPrice;

double CalculatePriceAfterDiscount(double discountRate = 20)
{
return originalPrice - (originalPrice * discountRate / 100);
}

double discountRate = 20.00; // 20%
originalPrice   = 198.75;

double priceAfterDiscount = CalculatePriceAfterDiscount();

WriteLine("Fun Department Store");
WriteLine("===================================");
WriteLine(\$"Orignial Price:  {originalPrice}");
WriteLine(\$"Discount Rate:   {discountRate}%");
WriteLine("-----------------------------------");
WriteLine(\$"Marked Price:    {priceAfterDiscount:F}");
WriteLine("===================================");```

This code would produce the same result as the previous one. Notice that the parentheses of the function are empty, which means that the argument was not passed. In the same way, you can create a function that uses many parameters and some or all of those parameters can have default values.

If a function 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 function, type each name followed by = and followed by the desired value. Here is an example:

```using static System.Console;

double originalPrice;

double CalculatePriceAfterDiscount(double discountRate = 20)
{
return originalPrice - (originalPrice * discountRate / 100);
}

double CalculateMarkedPrice(double price = 200.00,
double tax = 5.75,
double discount = 50.00)
{
double markedPrice;

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

return markedPrice;
}

double discountRate = 20.00; // 20%
originalPrice   = 198.75;

double priceAfterDiscount = CalculateMarkedPrice();

WriteLine("Fun Department Store");
WriteLine("===================================");
WriteLine(\$"Orignial Price:  {originalPrice}");
WriteLine(\$"Discount Rate:   {discountRate}%");
WriteLine("-----------------------------------");
WriteLine(\$"Marked Price:    {priceAfterDiscount:F}");
WriteLine("===================================");```

This would produce:

```Fun Department Store
===================================
Orignial Price:  198.75
Discount Rate:   20%
-----------------------------------
Marked Price:    105.75
===================================

Press any key to close this window . . .```

Rules on Parameters With Optional Values

If a function 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:

• If a function uses two parameters, 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 parameters, the parameter 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.
• If the function uses more than two parameters and you would like only some of those parameters to have default values, the parameter(s) that has(have) (a) default value(s) must be at the end of the list. When calling the function, you can provide a value for only the argument(s) that do(es) not have a default value

A Parameter by Reference

Introduction

By default, a function can return only 0 or 1 value. Sometimes, you want a function to return more than one value. The C# language provides various solutions. One option is to use a reference to a variable.

Passing an Argument by Value

When calling a function that takes one or more arguments, we provide the necessary value(s) for the parameter(s). This is because an argument is always required and the calling function must provide a valid value when calling such a function. 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 . . .```

Introduction to Passing an Argument by Reference

When you declare a variable in a program, the compiler reserves some space for that variable in the computer memory. The location of a variable in memory is referred to as its address. If you supply the argument using its name, the compiler only makes a copy of the argument's value and passes it to the called function. Although the called function 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 to modify the value of its parameter. If you want the called function 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.

Passing a Parameter in

When you are creating a function, 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 in an operation. Most of the time, the function 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, such a parameter is said to be passed "in".

To let you indicate that you are passing a parameter "in", 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, 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, use the 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; that is, in the body of the function, you cannot assign a value to the in variable. 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 that uses an 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.

Passing a Parameter Out

As mentioned above, most of the time, you are interested in a parameter for the value it is holding, in which case you simply involve the parameter in an operation in the body of the function. In some cases, you may want a function to change the value of a parameter. To offer a solution, the C# language provides the out keyword. As done with the in parameter, when creating a function, 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:

• In the body of the function, you must assign a value to the out-parameter. Here is an example:
```void GetWithdrawal(out double amount)
{
amount = 265.00;
}```
• When calling a function that takes an out argument, precede the argument with the out keyword

Before calling a function 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, 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, you must assign a value to the out-parameter), any modification made on the argument would be kept when the function ends. This characteristic makes it possible for a function to return many values, a feature not normally available to functions. 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 . . .```

A Reference to an Argument

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, 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 (remember that you neither have to declare a variable for an out parameter nor have to initialize it). When calling the function, (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 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 ends, the ref argument keeps its new value.

You can create a function that uses 0, one, or more parameters as reference(s). When we studied the fact that a function 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 use many parameters as references makes it possible for a function 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 number of tires 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.

Topics on Functions

Partial Class Implementation

In C#, you can create a class (the same class) in different files. This means that you can start a class in one file and continue it in another file or in other files. This is referred to as partial implementation.

As we have seen so far, in C#, you cannot simply and only declare a function in a file for a forward (later) implementation. In C#, to create a class in various files, start the class in one file but precede the class keyword with partial. Here is an example of a file named ResourcesPart.cs that contains some fields (member variables):

 Source File: ResourcesPart.cs ```partial class Person { public string FirstName; public string LastName; }```

After creating the class in one file, you can use it like any of the classes as we have done so far. Here is an example:

 Source File: Exercise.cs ```using static System.Console; Person pers = new Person(); pers.FirstName = "John"; pers.LastName = "Foster"; WriteLine("Personal Identification"); WriteLine("-----------------------"); Write("First Name: "); WriteLine(pers.FirstName); Write("Last Name: "); WriteLine(pers.LastName); WriteLine("=======================");```

This would produce:

```Personal Identification
-----------------------
First Name: John
Last Name:  Foster
=======================
Press any key to continue . . .```

If you had created a partial class, or you got a partial class from somebody (not as part of a DLL nor from another type of library), and you find out that the class is not complete, you can then complement it. There are rules you must follow:

• The partial class must have been marked as partial in its original creation, as we did above
• You must use the same name for the class
• You must precede the class keyword with partial

One of the advantages of partial implementation is that you don't have to get back to the first or previous file to modify it in order to complement the class. You can simply start another file and continue the class in it. Here is an example:

 Source File: Human.cs ```partial class Person { public string DateOfBirth; public string Gender; }```
 Source File: Exercise.cs ```using static System.Console; Person pers = new Person(); pers.FirstName = "John"; pers.LastName = "Foster"; pers.Gender = "Male"; pers.DateOfBirth = "10/04/2016"; WriteLine("Personal Identification"); WriteLine("-----------------------"); Write("First Name: "); WriteLine(pers.FirstName); Write("Last Name: "); WriteLine(pers.LastName); Write("Date of Birth: "); WriteLine(pers.Gender); Write("Gender: "); WriteLine(pers.DateOfBirth); WriteLine("=======================");```

This would produce:

```Personal Identification
-----------------------
First Name:     John
Last Name:      Foster
Date of Birth:  Male
Gender:         10/04/2016
=======================
Press any key to continue . . .```

Introduction to Recursion

Recursion if the ability for a function to call itself. A possible problem is that the function could keep calling itself and never stops. Therefore, the function must define how it would stop calling itself and get out of the body of the function.

A type of formula to create a recursive function is:

```return-value function-name(parameter(s), if any)
{
Optional Action . . .
function-name();
Optionan Action . . .
}```

A recursive function starts with a return value. If it would not return a value, you can define it with void. After its name, the function can use 0, one, or more parameters. Most of the time, a recursive function uses at least one parameter that it would modify. In the body of the function, you can take the necessary actions. There are no particular steps to follow when implementing a recursive function but there are two main rules to observe:

• In its body, the function must call itself
• Before or after calling itself, the function must check a condition that would allow it to stop, otherwise, it might run continuously

For an example of counting decrementing even numbers, you could start by creating a function that uses a parameter of type integer. To exercise some control on the lowest possible values, we will consider only positive numbers. In the body of the function, we will display the current value of the argument, subtract 2, and recall the function itself. Here is our function:

```using static System.Console;

int number = 0;

void EvenNumbers(int a)
{
if (a >= 1)
{
WriteLine("Even Number: {0}", a);

number += a;

a -= 2;
EvenNumbers(a);
}
}

// Calling a recursive function
EvenNumbers(34);

WriteLine("--------------------------------------------");
WriteLine("The total even numbers from 0 to 34 is: {0}", number);```

Notice that the function calls itself in its body. This would produce:

```Even Number: 34
Even Number: 32
Even Number: 30
Even Number: 28
Even Number: 26
Even Number: 24
Even Number: 22
Even Number: 20
Even Number: 18
Even Number: 16
Even Number: 14
Even Number: 12
Even Number: 10
Even Number: 8
Even Number: 6
Even Number: 4
Even Number: 2
--------------------------------------------
The total even numbers from 0 to 34 is: 306

Press any key to close this window . . .```

Practical Learning: Ending the Lesson

• Close your programming environment
 Previous Copyright © 2001-2022, FunctionX Saturday 13 November 2021 Next