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 LearningPractical 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:

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 LearningPractical 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 is > 0) && (grossSalary is <= 3_000))
        {
            first3000 = 0.00;
            next2000  = 0.00;
            next5000  = 0.00;
            over10000 = 0.00;
        }
        else if((grossSalary is > 3_000) && (grossSalary is <= 5_000))
        {
            first3000 = 0.00;
            next2000 = (grossSalary - 3_000) * 3 / 100;
            next5000 = 0.00;
            over10000 = 0.00;
        }
        else if((grossSalary is > 5_000) && (grossSalary is <= 10_000))
        {
            first3000 = 0.00;
            next2000 = 2_000 * 3 / 100;
            next5000 = (grossSalary - 5_000) * 4 / 100;
            over10000 = 0.00;
        }
        else // if(grossSalary is > 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 is > 0) && (grossSalary is <= 3_000))
            return 0.00;
        else if((grossSalary is > 3_000) && (grossSalary is <= 5_000))
            return (grossSalary - 3_000) * 3 / 100;
        else if((grossSalary is > 5_000) && (grossSalary is <= 10_000))
            return (2_000 * 3 / 100) + ((grossSalary - 5_000) * 4 / 100);
        else // if(grossSalary is > 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 TaxPreparation07 and accept or change the project Location
  21. Click Next
  22. Make sure the Target Framework combo box is displaying .NET 8.0 (Long-Term Support).
    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 LearningPractical Learning: Creating Functions With Many Parameters

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.

Author Note

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 LearningPractical 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.

ApplicationPractical 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:

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:

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:

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 LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2024, FunctionX Monday 17 April 2023 Next