A Parameter by Value

Introduction

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

Practical LearningPractical Learning: Introducing Parameters

  1. Start Microsoft Visual Studio
  2. Create a new Console App named PayrollPreparation3 that supports .NET 8.0 (Long-Term Support)
  3. In the Solution Explorer, right-click Program.cs and click Rename
  4. Type PayrollProcessing (to get PayrollProcessing.cs)
  5. Change the document in the PayrollProcessing.cs tab as follows:
    using static System.Console;
    
    PreparePayroll();
    
    // -------------------------------------------------------
    
    string GetFirstName()
    {
        WriteLine("FUN DEPARTMENT STORE");
        WriteLine("=======================================================");
        WriteLine("Payroll Preparation");
        WriteLine("-------------------------------------------------------");
        WriteLine("Enter the following pieces of information");
        WriteLine("-------------------------------------------------------");
        WriteLine("Employee Information");
        WriteLine("-------------------------------------------------------");
    
        Write("First Name:    ");
        string result = ReadLine();
    
        return result;
    }
    
    string GetLastName()
    {
        Write("Last Name:     ");
        string result = ReadLine();
    
        return result;
    }
    
    double GetBaseRate()
    {
        Write("Hourly Salary: ");
        double wages = double.Parse(ReadLine());
    
        return wages;
    }
    
    double GetMondayTimeWorked()
    {
        WriteLine("-------------------------------------------------------");
        WriteLine("Time worked");
        WriteLine("-------------------------------------------------------");
        Write("Monday:        ");
        double time = double.Parse(ReadLine());
        return time;
    }
    
    double GetTuesdayTimeWorked()
    {
        Write("Tuesday:       ");
        double time = double.Parse(ReadLine());
        return time;
    }
    
    double GetWednesdayTimeWorked()
    {
        Write("Wednesday:     ");
        double time = double.Parse(ReadLine());
        return time;
    }
    
    double GetThursdayTimeWorked()
    {
        Write("Thursday:      ");
        double time = double.Parse(ReadLine());
        return time;
    }
    
    double GetFridayTimeWorked()
    {
        Write("Friday:        ");
        double time = double.Parse(ReadLine());
        return time;
    }
    
    double Add2(double m, double n)
    {
        return m + n;
    }
    
    double Add5(double a, double b, double c, double d, double e)
    {
        return a + b + c + d + e;
    }

Passing a Parameter in

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 in the function, 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.

Practical LearningPractical Learning: Passing Parameters IN

  1. Change the document in the PayrollProcessing.cs tab as follows:
    using static System.Console;
    
    PreparePayroll();
    
    // -------------------------------------------------------
    
    string GetFirstName()
    {
        WriteLine("FUN DEPARTMENT STORE");
        WriteLine("=======================================================");
        WriteLine("Payroll Preparation");
        WriteLine("-------------------------------------------------------");
        WriteLine("Enter the following pieces of information");
        WriteLine("-------------------------------------------------------");
        WriteLine("Employee Information");
        WriteLine("-------------------------------------------------------");
    
        Write("First Name:    ");
        string result = ReadLine();
    
        return result;
    }
    
    string GetLastName()
    {
        Write("Last Name:     ");
        string result = ReadLine();
    
        return result;
    }
    
    double GetBaseRate()
    {
        Write("Hourly Salary: ");
        double wages = double.Parse(ReadLine());
    
        return wages;
    }
    
    double GetMondayTimeWorked()
    {
        WriteLine("-------------------------------------------------------");
        WriteLine("Time worked");
        WriteLine("-------------------------------------------------------");
        Write("Monday:        ");
        double time = double.Parse(ReadLine());
        return time;
    }
    
    double GetTuesdayTimeWorked()
    {
        Write("Tuesday:       ");
        double time = double.Parse(ReadLine());
        return time;
    }
    
    double GetWednesdayTimeWorked()
    {
        Write("Wednesday:     ");
        double time = double.Parse(ReadLine());
        return time;
    }
    
    double GetThursdayTimeWorked()
    {
        Write("Thursday:      ");
        double time = double.Parse(ReadLine());
        return time;
    }
    
    double GetFridayTimeWorked()
    {
        Write("Friday:        ");
        double time = double.Parse(ReadLine());
        return time;
    }
    
    double Add2(in double m, in double n)
    {
        return m + n;
    }
    
    double Add5(in double a, in double b, in double c, in double d, in double e)
    {
        return a + b + c + d + e;
    }
    
    double CalculateRegularTime(double time)
    {
        double result = time;
    
        if (time is > 40.00)
        {
            result = 40.00;
        }
    
        return result;
    }
    
    double CalculateRegularPay(double sal, double time)
    {
        double result = sal * time;
    
        if (time is > 40.00)
        {
            result = sal * 40.00;
        }
    
        return result;
    }
    
    double CalculateOvertime(double time)
    {
        double result = 0.00;
    
        if (time is > 40.00)
        {
            result = time - 40.00;
        }
    
        return result;
    }
    
    double CalculateOvertimePay(double sal, double time, double over)
    {
        double result = 0.00;
    
        if (time is > 40.00)
        {
            result = sal * 1.50 * over;
        }
    
        return result;
    }
    
    void PreparePayroll()
    {
        string firstName   = GetFirstName();
        string lastName    = GetLastName();
        double hSalary     = GetBaseRate();
    
        double mon         = GetMondayTimeWorked();
        double tue         = GetTuesdayTimeWorked();
        double wed         = GetWednesdayTimeWorked();
        double thu         = GetThursdayTimeWorked();
        double fri         = GetFridayTimeWorked();
    
        double timeWorked  = Add5(mon, tue, wed, thu, fri);
        double regularTime = CalculateRegularTime(timeWorked);
        double regularPay  = CalculateRegularPay(hSalary, timeWorked);
        double overtime    = CalculateOvertime(timeWorked);
        double overtimePay = CalculateOvertimePay(hSalary, timeWorked, overtime);
    
        double weeklyPay   = Add2(regularPay, overtimePay);
    
        WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+");
        WriteLine("FUN DEPARTMENT STORE");
        WriteLine("=======================================================");
        WriteLine("Payroll Evaluation");
        WriteLine("=======================================================");
        WriteLine("Employee Information");
        WriteLine("-------------------------------------------------------");
        WriteLine($"Full Name:     {firstName} {lastName}");
        WriteLine($"Hourly Salary: {hSalary:f}");
        WriteLine("=======================================================");
        WriteLine("Time Worked Summary");
        WriteLine("--------+---------+-----------+----------+-------------");
        WriteLine(" Monday | Tuesday | Wednesday | Thursday | Friday");
        WriteLine("--------+---------+-----------+----------+-------------");
        WriteLine($"  {mon:f}  |   {tue:f}  |    {wed:f}   |   {thu:f}   |  {fri:f}");
        WriteLine("========+=========+===========+==========+=============");
        WriteLine("                                    Pay Summary");
        WriteLine("-------------------------------------------------------");
        WriteLine("                                   Time   Pay");
        WriteLine("-------------------------------------------------------");
        WriteLine($"                     Regular:    {regularTime:f}   {regularPay:f}");
        WriteLine("-------------------------------------------------------");
        WriteLine($"                     Overtime:    {overtime:f}   {overtimePay:f}");
        WriteLine("=======================================================");
        WriteLine($"                     Net Pay:            {weeklyPay:f}");
        WriteLine("=======================================================");
    }
  2. To execute the project, press Ctrl + F5
  3. When requested, type the values as indicated and press Enter after each:
    FUN DEPARTMENT STORE
    =======================================================
    Payroll Preparation
    -------------------------------------------------------
    Enter the following pieces of information
    -------------------------------------------------------
    Employee Information
    -------------------------------------------------------
    First Name:    Michael
    Last Name:     Carlock
    Hourly Salary: 28.25
    -------------------------------------------------------
    Time worked
    -------------------------------------------------------
    Monday:        7
    Tuesday:       8
    Wednesday:     6.5
    Thursday:      8.5
    Friday:        6.5
    +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
    FUN DEPARTMENT STORE
    =======================================================
    Payroll Evaluation
    =======================================================
    Employee Information
    -------------------------------------------------------
    Full Name:     Michael Carlock
    Hourly Salary: 28.25
    =======================================================
    Time Worked Summary
    --------+---------+-----------+----------+-------------
     Monday | Tuesday | Wednesday | Thursday | Friday
    --------+---------+-----------+----------+-------------
      7.00  |   8.00  |    6.50   |   8.50   |  6.50
    ========+=========+===========+==========+=============
                                        Pay Summary
    -------------------------------------------------------
                                       Time   Pay
    -------------------------------------------------------
                         Regular:    36.50   1031.12
    -------------------------------------------------------
                         Overtime:    0.00   0.00
    =======================================================
                         Net Pay:            1031.12
    =======================================================
    
    Press any key to close this window . . .
  4. Return to your programming environment

A Parameter by Reference

Introduction

When calling a function that takes at least one argument, if you supply an argument using its name, the compiler only makes a copy of the argument's value and passes it to the called function. 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 Out

We have already seen that you can pass an argument using the in keyword. This indicates that you are interested in a parameter for the value it is holding and you will not change the value of the argument in the body of the function. 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:

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 (regular) 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 . . .

Practical LearningPractical Learning: Passing Parameters Out

  1. Change the PayrollProcessing.cs document as follows:
    using static System.Console;
    
    PreparePayroll();
    
    // -------------------------------------------------------
    
    void IdentifyEmployee(out string fn, out string ln, out double sal)
    {
        WriteLine("FUN DEPARTMENT STORE");
        WriteLine("=======================================================");
        WriteLine("Payroll Preparation");
        WriteLine("-------------------------------------------------------");
        WriteLine("Enter the following pieces of information");
        WriteLine("-------------------------------------------------------");
        WriteLine("Employee Information");
        WriteLine("-------------------------------------------------------");
    
        Write("First Name:    ");
        fn = ReadLine();
        Write("Last Name:     ");
        ln = ReadLine();
        Write("Hourly Salary: ");
        sal = double.Parse(ReadLine());
    }
    
    double GetMondayTimeWorked()
    {
        WriteLine("-------------------------------------------------------");
        WriteLine("Time worked");
        WriteLine("-------------------------------------------------------");
        Write("Monday:        ");
        double time = double.Parse(ReadLine());
        return time;
    }
    
    double GetTuesdayTimeWorked()
    {
        Write("Tuesday:       ");
        double time = double.Parse(ReadLine());
        return time;
    }
    
    double GetWednesdayTimeWorked()
    {
        Write("Wednesday:     ");
        double time = double.Parse(ReadLine());
        return time;
    }
    
    double GetThursdayTimeWorked()
    {
        Write("Thursday:      ");
        double time = double.Parse(ReadLine());
        return time;
    }
    
    double GetFridayTimeWorked()
    {
        Write("Friday:        ");
        double time = double.Parse(ReadLine());
        return time;
    }
    
    double Add2(in double m, in double n)
    {
        return m + n;
    }
    
    double Add5(in double a, in double b, in double c, in double d, in double e)
    {
        return a + b + c + d + e;
    }
    
    double CalculateRegularTime(double time)
    {
        double result = time;
    
        if (time is > 40.00)
        {
            result = 40.00;
        }
    
        return result;
    }
    
    double CalculateRegularPay(double sal, double time)
    {
        double result = sal * time;
    
        if (time is > 40.00)
        {
            result = sal * 40.00;
        }
    
        return result;
    }
    
    double CalculateOvertime(double time)
    {
        double result = 0.00;
    
        if (time is > 40.00)
        {
            result = time - 40.00;
        }
    
        return result;
    }
    
    double CalculateOvertimePay(double sal, double time, double over)
    {
        double result = 0.00;
    
        if (time is > 40.00)
        {
            result = sal * 1.50 * over;
        }
    
        return result;
    }
    
    void PreparePayroll()
    {
        string firstName;
        string lastName;
        double hSalary;
    
        IdentifyEmployee(out firstName, out lastName, out hSalary);
    
        double mon         = GetMondayTimeWorked();
        double tue         = GetTuesdayTimeWorked();
        double wed         = GetWednesdayTimeWorked();
        double thu         = GetThursdayTimeWorked();
        double fri         = GetFridayTimeWorked();
    
        double timeWorked  = Add5(mon, tue, wed, thu, fri);
        double regularTime = CalculateRegularTime(timeWorked);
        double regularPay  = CalculateRegularPay(hSalary, timeWorked);
        double overtime    = CalculateOvertime(timeWorked);
        double overtimePay = CalculateOvertimePay(hSalary, timeWorked, overtime);
    
        double weeklyPay   = Add2(regularPay, overtimePay);
    
        WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+");
        WriteLine("FUN DEPARTMENT STORE");
        WriteLine("=======================================================");
        WriteLine("Payroll Evaluation");
        WriteLine("=======================================================");
        WriteLine("Employee Information");
        WriteLine("-------------------------------------------------------");
        WriteLine($"Full Name:     {firstName} {lastName}");
        WriteLine($"Hourly Salary: {hSalary:f}");
        WriteLine("=======================================================");
        WriteLine("Time Worked Summary");
        WriteLine("--------+---------+-----------+----------+-------------");
        WriteLine(" Monday | Tuesday | Wednesday | Thursday | Friday");
        WriteLine("--------+---------+-----------+----------+-------------");
        WriteLine($"  {mon:f}  |   {tue:f}  |    {wed:f}   |   {thu:f}   |  {fri:f}");
        WriteLine("========+=========+===========+==========+=============");
        WriteLine("                                    Pay Summary");
        WriteLine("-------------------------------------------------------");
        WriteLine("                                   Time   Pay");
        WriteLine("-------------------------------------------------------");
        WriteLine($"                     Regular:    {regularTime:f}   {regularPay:f}");
        WriteLine("-------------------------------------------------------");
        WriteLine($"                     Overtime:    {overtime:f}   {overtimePay:f}");
        WriteLine("=======================================================");
        WriteLine($"                     Net Pay:            {weeklyPay:f}");
        WriteLine("=======================================================");
    }
  2. Press Ctrl + F5 to execute again
  3. Type the requested values and press Enter after each value:
    FUN DEPARTMENT STORE
    =======================================================
    Payroll Preparation
    -------------------------------------------------------
    Enter the following pieces of information
    -------------------------------------------------------
    Employee Information
    -------------------------------------------------------
    First Name:    Catherine
    Last Name:     Busbey
    Hourly Salary: 24.37
    -------------------------------------------------------
    Time worked
    -------------------------------------------------------
    Monday:        9.5
    Tuesday:       8
    Wednesday:     10.5
    Thursday:      9
    Friday:        8.5
    +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
    FUN DEPARTMENT STORE
    =======================================================
    Payroll Evaluation
    =======================================================
    Employee Information
    -------------------------------------------------------
    Full Name:     Catherine Busbey
    Hourly Salary: 24.37
    =======================================================
    Time Worked Summary
    --------+---------+-----------+----------+-------------
     Monday | Tuesday | Wednesday | Thursday | Friday
    --------+---------+-----------+----------+-------------
      9.50  |   8.00  |    10.50   |   9.00   |  8.50
    ========+=========+===========+==========+=============
                                        Pay Summary
    -------------------------------------------------------
                                       Time   Pay
    -------------------------------------------------------
                         Regular:    40.00   974.80
    -------------------------------------------------------
                         Overtime:    5.50   201.05
    =======================================================
                         Net Pay:            1175.85
    =======================================================
    
    Press any key to close this window . . .
  4. Return to your programming environment

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 the ref keyword to which we were introduced already. 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.

Practical LearningPractical Learning: Passing Arguments by Reference

  1. Change the PayrollProcessing.cs document as follows:
    using static System.Console;
    
    PreparePayroll();
    
    // -------------------------------------------------------
    
    void IdentifyEmployee(out string fn, out string ln, out double sal)
    {
        WriteLine("FUN DEPARTMENT STORE");
        WriteLine("=======================================================");
        WriteLine("Payroll Preparation");
        WriteLine("-------------------------------------------------------");
        WriteLine("Enter the following pieces of information");
        WriteLine("-------------------------------------------------------");
        WriteLine("Employee Information");
        WriteLine("-------------------------------------------------------");
    
        Write("First Name:    ");
        fn = ReadLine();
        Write("Last Name:     ");
        ln = ReadLine();
        Write("Hourly Salary: ");
        sal = double.Parse(ReadLine());
    }
    
    void GetTimeWorked(ref double m, ref double t, ref double w, ref double h, ref double f)
    {
        WriteLine("-------------------------------------------------------");
        WriteLine("Time worked");
        WriteLine("-------------------------------------------------------");
        Write("Monday:        ");
        m = double.Parse(ReadLine());
        Write("Tuesday:       ");
        t = double.Parse(ReadLine());
        Write("Wednesday:     ");
        w = double.Parse(ReadLine());
        Write("Thursday:      ");
        h = double.Parse(ReadLine());
        Write("Friday:        ");
        f = double.Parse(ReadLine());
    }
    
    double Add2(in double m, in double n)
    {
        return m + n;
    }
    
    double Add5(in double a, in double b, in double c, in double d, in double e)
    {
        return a + b + c + d + e;
    }
    
    void EvaluateSalary(double time, double sal,
                        ref double regTime, ref double regPay, ref double overtime, ref double overPay)
    {
        regTime = time;
        regPay = sal * time;
        overtime = 0.00;
        overPay = 0.00;
    
        if (time is > 40.00)
        {
            regTime = 40.00;
            regPay = sal * 40.00;
            overtime = time - 40.00;
            overPay = sal * 1.50 * overtime;
        }
    }
    
    void PreparePayroll()
    {
        string firstName;
        string lastName;
        double hSalary;
    
        double mon         = 0.00;
        double tue         = 0.00;
        double wed         = 0.00;
        double thu         = 0.00;
        double fri         = 0.00;
    
        double regularTime = 0.00;
        double regularPay  = 0.00;
        double overtime    = 0.00;
        double overtimePay = 0.00;
    
        IdentifyEmployee(out firstName, out lastName, out hSalary);
        GetTimeWorked(ref mon, ref tue, ref wed, ref thu, ref fri);
    
        double timeWorked  = Add5(mon, tue, wed, thu, fri);
    
        EvaluateSalary(timeWorked, hSalary,
                       ref regularTime, ref regularPay, ref overtime, ref overtimePay);
    
        double weeklyPay  = Add2(regularPay, overtimePay);
    
        WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+");
        WriteLine("FUN DEPARTMENT STORE");
        WriteLine("=======================================================");
        WriteLine("Payroll Evaluation");
        WriteLine("=======================================================");
        WriteLine("Employee Information");
        WriteLine("-------------------------------------------------------");
        WriteLine($"Full Name:     {firstName} {lastName}");
        WriteLine($"Hourly Salary: {hSalary:f}");
        WriteLine("=======================================================");
        WriteLine("Time Worked Summary");
        WriteLine("--------+---------+-----------+----------+-------------");
        WriteLine(" Monday | Tuesday | Wednesday | Thursday | Friday");
        WriteLine("--------+---------+-----------+----------+-------------");
        WriteLine($"  {mon:f}  |   {tue:f}  |    {wed:f}   |   {thu:f}   |  {fri:f}");
        WriteLine("========+=========+===========+==========+=============");
        WriteLine("                                    Pay Summary");
        WriteLine("-------------------------------------------------------");
        WriteLine("                                   Time   Pay");
        WriteLine("-------------------------------------------------------");
        WriteLine($"                     Regular:    {regularTime:f}   {regularPay:f}");
        WriteLine("-------------------------------------------------------");
        WriteLine($"                     Overtime:    {overtime:f}   {overtimePay:f}");
        WriteLine("=======================================================");
        WriteLine($"                     Net Pay:            {weeklyPay:f}");
        WriteLine("=======================================================");
    }
  2. To execute, press Ctrl + F5
  3. Type some values and press Enter after each value:
    FUN DEPARTMENT STORE
    =======================================================
    Payroll Preparation
    -------------------------------------------------------
    Enter the following pieces of information
    -------------------------------------------------------
    Employee Information
    -------------------------------------------------------
    First Name:    Andrew
    Last Name:     Sanders
    Hourly Salary: 26.97
    -------------------------------------------------------
    Time worked
    -------------------------------------------------------
    Monday:        9
    Tuesday:       10.50
    Wednesday:     7
    Thursday:      9.50
    Friday:        8.50
    +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
    FUN DEPARTMENT STORE
    =======================================================
    Payroll Evaluation
    =======================================================
    Employee Information
    -------------------------------------------------------
    Full Name:     Andrew Sanders
    Hourly Salary: 26.97
    =======================================================
    Time Worked Summary
    --------+---------+-----------+----------+-------------
     Monday | Tuesday | Wednesday | Thursday | Friday
    --------+---------+-----------+----------+-------------
      9.00  |   10.50  |    7.00   |   9.50   |  8.50
    ========+=========+===========+==========+=============
                                        Pay Summary
    -------------------------------------------------------
                                       Time   Pay
    -------------------------------------------------------
                         Regular:    40.00   1078.80
    -------------------------------------------------------
                         Overtime:    4.50   182.05
    =======================================================
                         Net Pay:            1260.85
    =======================================================
    
    Press any key to close this window . . .
  4. Return to your programming environment

A Read-Only Referenced Argument

Most of the time, the reason you want to pass an argument by reference is because you want its function to change the value of that argument, making it possible for the function to return more than one value. In some cases, you may not want the function to change the value of the argument, as is the case for an in argument. If you don't want a function to be able to change the value of a referenced argument, or to inform the compiler that you don't want the function to change the value of a referenced argument, you can pass the argument as read-only. To do this, when creating the function, between the ref keyword and the data type of the parameter, add the readonly keyword. When calling the function, you must pass the argument as a reference, by preceding the argument (only) the ref keyword. This can be done as follows:

using static System.Console;

void Present(ref readonly double val)
{
    WriteLine("Value: {0}", val);
}

double @double = 397_822.73;

Present(ref @double);

WriteLine("===================================");

This would produce:

Value: 397822.73
===================================

Press any key to close this window . . .

Remember that, if you pass an argument as ref readonly, you are not allowed to change the value of the argument in the body of the function. If you do, the compiler will produce an error.

Practical LearningPractical Learning: Passing Arguments as Read-Only References

  1. Change the PayrollProcessing.cs document as follows:
    using static System.Console;
    
    PreparePayroll();
    
    // -------------------------------------------------------
    
    void IdentifyEmployee(out string fn, out string ln, out double sal)
    {
        WriteLine("FUN DEPARTMENT STORE");
        WriteLine("=======================================================");
        WriteLine("Payroll Preparation");
        WriteLine("-------------------------------------------------------");
        WriteLine("Enter the following pieces of information");
        WriteLine("-------------------------------------------------------");
        WriteLine("Employee Information");
        WriteLine("-------------------------------------------------------");
    
        Write("First Name:    ");
        fn = ReadLine();
        Write("Last Name:     ");
        ln = ReadLine();
        Write("Hourly Salary: ");
        sal = double.Parse(ReadLine());
    }
    
    void GetTimeWorked(ref double m, ref double t, ref double w, ref double h, ref double f)
    {
        WriteLine("-------------------------------------------------------");
        WriteLine("Time worked");
        WriteLine("-------------------------------------------------------");
        Write("Monday:        ");
        m = double.Parse(ReadLine());
        Write("Tuesday:       ");
        t = double.Parse(ReadLine());
        Write("Wednesday:     ");
        w = double.Parse(ReadLine());
        Write("Thursday:      ");
        h = double.Parse(ReadLine());
        Write("Friday:        ");
        f = double.Parse(ReadLine());
    }
    
    double Add2(ref readonly double m, ref readonly double n)
    {
        return m + n;
    }
    
    double Add5(in double a, in double b, in double c, in double d, in double e)
    {
        return a + b + c + d + e;
    }
    
    void EvaluateSalary(ref readonly double time, ref readonly double sal,
                        ref double regTime, ref double regPay, ref double overtime, ref double overPay)
    {
        regTime = time;
        regPay = sal * time;
        overtime = 0.00;
        overPay = 0.00;
    
        if (time is > 40.00)
        {
            regTime = 40.00;
            regPay = sal * 40.00;
            overtime = time - 40.00;
            overPay = sal * 1.50 * overtime;
        }
    }
    
    void PreparePayroll()
    {
        string firstName;
        string lastName;
        double hSalary;
    
        double mon         = 0.00;
        double tue         = 0.00;
        double wed         = 0.00;
        double thu         = 0.00;
        double fri         = 0.00;
    
        double regularTime = 0.00;
        double regularPay  = 0.00;
        double overtime    = 0.00;
        double overtimePay = 0.00;
    
        IdentifyEmployee(out firstName, out lastName, out hSalary);
        GetTimeWorked(ref mon, ref tue, ref wed, ref thu, ref fri);
    
        double timeWorked  = Add5(in mon, in tue, in wed, in thu, in fri);
    
        EvaluateSalary(ref timeWorked, ref hSalary,
                       ref regularTime, ref regularPay, ref overtime, ref overtimePay);
    
        double weeklyPay  = Add2(ref regularPay, ref  overtimePay);
    
        WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+");
        WriteLine("FUN DEPARTMENT STORE");
        WriteLine("=======================================================");
        WriteLine("Payroll Evaluation");
        WriteLine("=======================================================");
        WriteLine("Employee Information");
        WriteLine("-------------------------------------------------------");
        WriteLine($"Full Name:     {firstName} {lastName}");
        WriteLine($"Hourly Salary: {hSalary:f}");
        WriteLine("=======================================================");
        WriteLine("Time Worked Summary");
        WriteLine("--------+---------+-----------+----------+-------------");
        WriteLine(" Monday | Tuesday | Wednesday | Thursday | Friday");
        WriteLine("--------+---------+-----------+----------+-------------");
        WriteLine($"  {mon:f}  |   {tue:f}  |    {wed:f}   |   {thu:f}   |  {fri:f}");
        WriteLine("========+=========+===========+==========+=============");
        WriteLine("                                    Pay Summary");
        WriteLine("-------------------------------------------------------");
        WriteLine("                                   Time   Pay");
        WriteLine("-------------------------------------------------------");
        WriteLine($"                     Regular:    {regularTime:f}   {regularPay:f}");
        WriteLine("-------------------------------------------------------");
        WriteLine($"                     Overtime:    {overtime:f}   {overtimePay:f}");
        WriteLine("=======================================================");
        WriteLine($"                     Net Pay:            {weeklyPay:f}");
        WriteLine("=======================================================");
    }
  2. To execute, press Ctrl + F5
  3. Type some values and press Enter after each value:
    FUN DEPARTMENT STORE
    =======================================================
    Payroll Preparation
    -------------------------------------------------------
    Enter the following pieces of information
    -------------------------------------------------------
    Employee Information
    -------------------------------------------------------
    First Name:    Jennifer
    Last Name:     Simms
    Hourly Salary: 31.57
    -------------------------------------------------------
    Time worked
    -------------------------------------------------------
    Monday:        8
    Tuesday:       8
    Wednesday:     8
    Thursday:      8
    Friday:        8
    +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
    FUN DEPARTMENT STORE
    =======================================================
    Payroll Evaluation
    =======================================================
    Employee Information
    -------------------------------------------------------
    Full Name:     Jennifer Simms
    Hourly Salary: 31.57
    =======================================================
    Time Worked Summary
    --------+---------+-----------+----------+-------------
     Monday | Tuesday | Wednesday | Thursday | Friday
    --------+---------+-----------+----------+-------------
      8.00  |   8.00  |    8.00   |   8.00   |  8.00
    ========+=========+===========+==========+=============
                                        Pay Summary
    -------------------------------------------------------
                                       Time   Pay
    -------------------------------------------------------
                         Regular:    40.00   1262.80
    -------------------------------------------------------
                         Overtime:    0.00   0.00
    =======================================================
                         Net Pay:            1262.80
    =======================================================
    
    Press any key to close this window . . .
  4. Press any key to close the window and return to your programming environment
  5. Close Microsoft Visual Studio

Previous Copyright © 2024, FunctionX Friday 19 January 2024 Next