Introduction to Parameters and Arguments
Introduction to Parameters and Arguments
Introduction to Parameters and Arguments
Introduction to the Parameters of a Function
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)
{
}
Remember that you can create a function in an @functions or an @{} section:
@functions{ 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:
@functions{ string ProtectFromBadWeather(string typeOfRoof) { return $"Roof Type: {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
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:
@page
@model Valuable.Pages.FoundationsModel
@{
}
@functions{
string propertyType = "Single Family";
int bedrooms = 5;
double marketValue = 482995;
string ProtectFromBadWeather(string typeOfRoof)
{
return $"Roof Type: {typeOfRoof}";
}
}
<pre>=//= Altair Realtors =//=
Properties Inventory
Property Type: @propertyType
@ProtectFromBadWeather("Asphalt Shingles")
Bedrooms: @bedrooms
Market Value: @marketValue</pre>
This would produce:
=//= Altair Realtors =//= Properties Inventory Property Type: Single Family Roof Type: Asphalt Shingles Bedrooms: 5 Market Value: 482995
If the value is stored in a variable, you can pass the name of the variable to the function. Here is an example:
@page @model Valuable.Pages.FoundationsModel @{ } @functions{ string propertyType = "Single Family"; int bedrooms = 5; double marketValue = 482995; string roofMaterial = "Affiche Shingles"; string ProtectFromBadWeather(string typeOfRoof) { return $"Roof Type: {typeOfRoof}"; } } <pre>=//= Altair Realtors =//= Properties Inventory Property Type: @propertyType @ProtectFromBadWeather(roofMaterial) Bedrooms: @bedrooms Market Value: @marketValue</pre>
Practical Learning: Introducing Parameters
@page @model TaxPreparation01.Pages.ProductDeliveryModel @{ double grossSalary = 12464.85; double taxAmount = EvaluateTaxLiability(grossSalary); string strGrossSalary = $"{grossSalary:f}"; string strFirst3000 = $"{first3000:f}"; string strNext2000 = $"{next2000:f}"; string strNext5000 = $"{next5000:f}"; string strOver10000 = $"{over10000:f}"; string strTaxAmount = $"{taxAmount:f}"; string strNetPay = $"{CalculateSalary(grossSalary):f}"; } @functions{ 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. */ 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); } } <pre>======================================== - Amazing DeltaX - State Income Tax - ---------------------------------------- -=- Mississippi -=- ======================================== Gross Salary: @strGrossSalary ---------------------------------------- First $3000: @strFirst3000 Next $2000: @strNext2000 Next $5000: @strNext5000 Over $10,000: @strOver10000 ---------------------------------------- Tax Amount: @strTaxAmount Net Pay: @strNetPay ========================================</pre>
======================================== - 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 ========================================
@page
@model TaxPreparation01.Pages.ColoradoModel
@{
}
@functions{
string GetFilingStatus()
{
return "";
}
double GetGrossSalary()
{
return 0.00;
}
double taxAmount = 0.00;
double net_pay = 0.00;
}
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
@page
@model TaxPreparation01.Pages.ColoradoModel
@{
}
@functions{
string GetFilingStatus()
{
return "";
}
double GetGrossSalary()
{
return 0.00;
}
double CalculateTaxAmount(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
@page @model TaxPreparation01.Pages.ColoradoModel @{ string filingStatus = GetFilingStatus(); double grossSalary = GetGrossSalary(); double taxAmount = CalculateTaxAmount(grossSalary); double netPay = CalculateNetPay(grossSalary, taxAmount); string strGrossSalary = $"{grossSalary:f}"; string strFilingStatus = $"{filingStatus}"; string strTaxAmount = $"{taxAmount:f}"; string strNetPay = $"{netPay:f}"; } @functions{ string GetFilingStatus() { /* Filing Status * i - Single * s - Married Filing Separate * j - Married Filing Joint or Head of Household */ return "Married Filing Joint or Head of Household"; } double GetGrossSalary() { double grossSalary = 1668.85; return grossSalary; } double CalculateTaxAmount(double salary) { double taxRate = 4.63; return salary * taxRate / 100.00; } double CalculateNetPay(double salary, double tax) { return salary - tax; } } <pre>========================================================= - Amazing DeltaX - State Income Tax - --------------------------------------------------------- -=- Colorado -=- ========================================================= Gross Salary: @strGrossSalary Filing Status: @strFilingStatus --------------------------------------------------------- Tax Amount: @strTaxAmount Net Pay: @strNetPay =========================================================</pre>
========================================================= - Amazing DeltaX - State Income Tax - --------------------------------------------------------- -=- Colorado -=- ========================================================= Gross Salary: 1668.85 Filing Status: Married Filing Joint or Head of Household --------------------------------------------------------- Tax Amount: 77.27 Net Pay: 1591.58 =========================================================
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
@page @model TaxPreparation01.Pages.ColoradoModel @{ string filingStatus = GetFilingStatus(); double grossSalary = GetGrossSalary(); double taxAmount = CalculateTaxAmount(salary: grossSalary); double netPay = CalculateNetPay(tax: taxAmount, salary: grossSalary); string strGrossSalary = $"{grossSalary:f}"; string strFilingStatus = $"{filingStatus}"; string strTaxAmount = $"{taxAmount:f}"; string strNetPay = $"{netPay:f}"; } @functions{ string GetFilingStatus() { /* Filing Status * i - Single * s - Married Filing Separate * j - Married Filing Joint or Head of Household */ return "Married Filing Separate"; } double GetGrossSalary() { double grossSalary = 3057.63; return grossSalary; } double CalculateTaxAmount(double salary) { double taxRate = 4.63; return salary * taxRate / 100.00; } double CalculateNetPay(double salary, double tax) { return salary - tax; } } <pre>========================================================= - Amazing DeltaX - State Income Tax - --------------------------------------------------------- -=- Colorado -=- ========================================================= Gross Salary: @strGrossSalary Filing Status: @strFilingStatus --------------------------------------------------------- Tax Amount: @strTaxAmount Net Pay: @strNetPay =========================================================</pre>
========================================================= - Amazing DeltaX - State Income Tax - --------------------------------------------------------- -=- Colorado -=- ========================================================= Gross Salary: 3057.63 Filing Status: Married Filing Separate --------------------------------------------------------- Tax Amount: 141.57 Net Pay: 2916.06 =========================================================
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:
@page @model Valuable.Pages.FoundationsModel @{ } @{ double originalPrice; double CalculatePriceAfterDiscount(double discountRate) { return originalPrice - (originalPrice * discountRate / 100); } double discountRate = 20.00; // 20% originalPrice = 198.75; double priceAfterDiscount = CalculatePriceAfterDiscount(discountRate); string strPrice = $"{priceAfterDiscount:F}"; } <pre>Fun Department Store =================================== Orignial Price: @originalPrice Discount Rate: @discountRate% ----------------------------------- Marked Price: @strPrice</pre>
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:
@page
@model Valuable.Pages.FoundationsModel
@{
}
@{
double originalPrice;
double CalculatePriceAfterDiscount(double discountRate = 20)
{
return originalPrice - (originalPrice * discountRate / 100);
}
double discountRate = 20.00; // 20%
originalPrice = 198.75;
double priceAfterDiscount = CalculatePriceAfterDiscount();
string strPrice = $"{priceAfterDiscount:F}";
}
<pre>Fun Department Store
===================================
Orignial Price: @originalPrice
Discount Rate: @discountRate%
-----------------------------------
Marked Price: @strPrice</pre>
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:
@page
@model Valuable.Pages.FoundationsModel
@{
}
@{
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();
string strPrice = $"{priceAfterDiscount:f}";
}
<pre>Fun Department Store
=================================
Orignial Price: @originalPrice
Discount Rate: @discountRate %
---------------------------------
Marked Price: @strPrice</pre>
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:
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:
@page @model Valuable.Pages.FoundationsModel @{ } @{ 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); string strPrice = $"{markedValue:F}"; } <pre>Fun Department Store =================================== Orignial Price: @cost Discount Rate: @dRate % ----------------------------------- Discount Amount: @discount Marked Price: @strPrice</pre>
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:
@page @model Valuable.Pages.FoundationsModel @{ } @{ double Subtract(in double a, in double b) { return a - b; } double CalculateDiscount(in double price, in double rate) { return price * rate / 100.00; } double cost = 169.95; int dRate = 25; double discount = CalculateDiscount(cost, dRate); double markedValue = Subtract(cost, discount); string strPrice = $"{markedValue:F}"; } <pre>Fun Department Store =================================== Orignial Price: @cost Discount Rate: @dRate % ----------------------------------- Discount Amount: @discount Marked Price: @strPrice</pre>
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.
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:
void GetWithdrawal(out double amount) { amount = 265.00; }
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:
@page @model Valuable.Pages.FoundationsModel @{ string description = "Nothing"; } <pre>Fun Department Store Item Description ------------------------------------------------------- Item Name: @description</pre> @{ void GetItemName(out string name) { name = "Blue Stripped Dress"; } GetItemName(out description); } <pre>================================================== Fun Department Store Item Description ------------------------------------------------------- Item Name: @description</pre>
Here is an example of running the application:
Fun Department Store Item Description ------------------------------------------------------- Item Name: Nothing Fun Department Store Item Description ------------------------------------------------------- Item Name: Blue Stripped Dress
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:
@page @model Valuable.Pages.FoundationsModel @{ void GetItemName(out string name) { name = "Blue Stripped Dress"; } void PrepareSale(out double price, out double rate) { price = 54.75; rate = 25.00; } string description = "Nothing"; double cost = 0.00, discount = 0.00; GetItemName(out description); PrepareSale(out cost, out discount); string strCost = $"{cost:F}"; string strDiscountRate = $"{(discount / 100.00):P}"; } <pre>Fun Department Store Item Description -------------------------------- Item Name: @description Marked Price: @strCost Discount Rate: @strDiscountRate</pre>
This would produce:
Fun Department Store Item Description -------------------------------- Item Name: Blue Stripped Dress Marked Price: 54.75 Discount Rate: 25.00%
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:
@page @model Valuable.Pages.FoundationsModel @{ void GetTimeWorked(ref double mon, ref double tue, ref double wed, ref double thu, ref double fri) { mon = 8.5; tue = 9; wed = 7.5; thu = 6; fri = 9.5; } 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); string strMonday = $"{a:f}"; string strTuesday = $"{b:f}"; string strWednesday = $"{c:f}"; string strThursday = $"{d:f}"; string strFriday = $"{e:F}"; } <pre>Fun Department Store Time Worked ------------------------- Monday: @strMonday Tuesday: @strTuesday Wednesday: @strWednesday Thursday: @strThursday Friday: @strFriday</pre>
This would produce:
Fun Department Store Time Worked ------------------------- Monday: 8.50 Tuesday: 9.00 Wednesday: 7.50 Thursday: 6.00 Friday: 9.50
You can create a function that receives regular parameters and parameters by reference. This creates a lot of flexibility in your applications.
Practical Learning: Ending the Lesson
|
|||
Previous | Copyright © 2001-2023, FunctionX | Saturday 13 November 2021 | Next |
|