Tuples and Functions

A Value from a Function

We already know that we you can create a function that returns a value. You can call such a function and assign its return value to a variable, then use that variable as an item of a tuple. Here is the example:

using static System.Console;

double EvaluateSalary(double hourly)
{
    return hourly * 40;
}

int emplNbr = 138_475;
double weeklySalary = 22.27;
string fName = "Christoffer";
string lName = "Prize";

double sal = EvaluateSalary(weeklySalary);

(int emplNumber, string fullName, double salary) employee = (emplNbr, fName + " " + lName, sal);

WriteLine("Employee Record");
WriteLine("---------------------------------------");
WriteLine($"Employee #:    {employee.emplNumber}");
WriteLine($"Full Name:     {employee.fullName}");
WriteLine($"Weekly Salary: {employee.salary}");
WriteLine("=======================================");

The value of a member of a tuple can come from a function. In the above example, we first called a function and assigned its return value to a value. This may be necessary if you need to use the return value many times. Otherwise, you can call the function where the value of the tuple element is accessed. Here is an example:

using static System.Console;

double EvaluateSalary(double hourly)
{
    return hourly * 40;
}

int emplNbr = 138_475;
double weeklySalary = 22.27;
string fName = "Christoffer";
string lName = "Prize";

(int emplNumber, string fullName, double salary) employee =
    (emplNbr, fName + " " + lName, EvaluateSalary(weeklySalary));

WriteLine("Employee Record");
WriteLine("---------------------------------------");
WriteLine($"Employee #:    {employee.emplNumber}");
WriteLine($"Full Name:     {employee.fullName}");
WriteLine($"Weekly Salary: {employee.salary}");
WriteLine("=======================================");

This would produce:

Employee Record
---------------------------------------
Employee #:    138475
Full Name:     Christoffer Prize
Weekly Salary: 890.8
=======================================

Press any key to close this window . . .

Practical LearningPractical Learning: Introducing Tuples

  1. Start Microsoft Visual Studio
  2. Create a new Console App named PayrollPreparation5 that supports .NET 9.0 (Standard 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(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("=======================================================");
    }
  6. To execute the project, press Ctrl + F5
  7. 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:    Jeannette
    Last Name:     Dobson
    Hourly Salary: 19.07
    -------------------------------------------------------
    Time worked
    -------------------------------------------------------
    Monday:        7
    Tuesday:       6
    Wednesday:     8
    Thursday:      6
    Friday:        7
    =======================================================
    FUN DEPARTMENT STORE
    =======================================================
    Payroll Evaluation
    =======================================================
    Employee Information
    -------------------------------------------------------
    Full Name:     Jeannette Dobson
    Hourly Salary: 19.07
    =======================================================
    Time Worked Summary
    --------+---------+-----------+----------+-------------
     Monday | Tuesday | Wednesday | Thursday | Friday
    --------+---------+-----------+----------+-------------
      7.00  |   6.00  |    8.00   |   6.00   |  7.00
    ========+=========+===========+==========+=============
                                        Pay Summary
    -------------------------------------------------------
                                       Time   Pay
    -------------------------------------------------------
                         Regular:    34.00   648.38
    -------------------------------------------------------
                         Overtime:    0.00   0.00
    =======================================================
                         Net Pay:            648.38
    =======================================================
    
    Press any key to close this window . . .
  8. Return to your programming environment

Passing a Tuple as Parameter

If you have a group of values that you want a function to process, instead of passing those values individually, you can pack those values in a tuple. In other words, you can create a function that takes a tuple as argument.

To make a function process a tuple, when creating the function, in its parentheses, type the parentheses for a tuple, followed by a name for the parameter. In the parentheses of the tuple, enter the data type of each member of the tuple and separate them with commas. Here is an example:

void Calculate((int, double, string) parameter)
{
}

In the body of the function, to access the tuple, use the name of the parameter. To access a member of the tuple, in the body of the function, type the name of the parameter, a period, and the name of the desired member. Here is an example:

using static System.Console;

int EvaluateDiscountRate(int days)
{
    int discountRate = 0;

    if (days > 70)
        discountRate = 70;
    else if (days > 50)
        discountRate = 50;
    else if (days > 30)
        discountRate = 35;
    else if (days > 15)
        discountRate = 15;

    return discountRate;
}

double EvaluateDiscountAmount((double cost, int rate) value)
{
    double discountAmount = value.cost * value.rate / 100.00;
        
    return discountAmount;
}

(double price, int reduction) itemInfo;
(int number, string name, double price, int days) storeItem;

WriteLine("Enter the values of the store item");
WriteLine("---------------------------------------------------");
Write("Item #:        ");
storeItem.number = int.Parse(ReadLine());
Write("Item Name:     ");
storeItem.name = ReadLine();
Write("Days in Store: ");
storeItem.days = int.Parse(ReadLine());
Write("Unit Price:    ");
storeItem.price = double.Parse(ReadLine());

int discountRate = exo.EvaluateDiscountRate(storeItem.days);

itemInfo.price = storeItem.price;
itemInfo.reduction = discountRate;
double discountedAmount = exo.EvaluateDiscountAmount(itemInfo);
        
double markedPrice = storeItem.price - discountedAmount;

WriteLine("===================================================");
WriteLine("Fun Department Store");
WriteLine("---------------------------------------------------");
WriteLine($"Item #:          {storeItem.number}");
WriteLine($"Item Name:       {storeItem.name}");
WriteLine($"Days in Store:   {storeItem.days}");
WriteLine($"Original Price:  {storeItem.price:f}");
WriteLine("---------------------------------------------------");
WriteLine($"Discount Rate:   {discountRate}%");
WriteLine($"Discount Amount: {discountedAmount:f}");
WriteLine($"Marked Price:    {markedPrice:f}");
WriteLine("===================================================");

Here is an example of running the program:

Enter the values of the store item
---------------------------------------------------
Item #:        9370592
Item Name:     Summer Casual V-Neck Floral Dress
Days in Store: 38
Unit Price:    98.85
===================================================
Fun Department Store
---------------------------------------------------
Item #:          9370592
Item Name:       Summer Casual V-Neck Floral Dress
Days in Store:   38
Original Price:  98.85
---------------------------------------------------
Discount Rate:   35%
Discount Amount: 34.60
Marked Price:    64.25
===================================================

Press any key to close this window . . .

As seen with using tuples on a function, if you provided only the data types of the members of the tuple parameter, access the members with their incrementing names: Item1, Item2, etc. As an alternative, you can provide a name for one or more members of the tuple parameters.

Passing Many Tuples to a Function

We saw that you can pass a tuple to a function. In the same way, you can pass a combination of a tuple and parameters of regular types to a method. Here is an example:

void Examine(int id, (string title, string description) issue, bool resolved)
{

}

In the same way, you can create a function that takes more than one tuple as parameters. Here is an example:

void Examine(int id, (string title, string description) issue, bool resolved, (string memory, double price) description)
{

}

Returning a Tuple

Instead of a regular single value, a function can be made to return a tuple, which is a combination of values. This is one of the most important features of tuples.

When creating a function, to indicate that it must produce a tuple, on the left side of the name of the function, type a tuple. Here is an example:

(string, int, string, double) Summarize()
{

}

In the body of the function, on the last line, type the return keyword, followed by a tuple that uses a combination of values of the exact same type declared for the return value of the function. Here is an example

(string, int, string, double) Summarize()
{
    return ("John", 10, "Doe", 1.00);
}

Otherwise, in the body of the function, you can perform any operation you want. For example, you can declare variables of any type and use them any way you want. In fact, you can return a tuple that uses such local variables. Here is an example:

(string, int, string, double) Summarize()
{
    double salary = 52_846;
    int    code   = 293_704;
    string first  = "John", last = "Doe";

    return (first, code, last, salary);
}

The return tuple can also use one or more expressions. Here is an example:

(int, string, double) Summarize()
{
    double hourSalary = 22.86;
    int    code       = 293_704;
    string first      = "John", last = "Doe";

    /* Yearly Salary = Hourly Salary *  8 (= Daily Salary)
                                     *  5 (= Weekly Salary)
                                     *  4 (= Monthly Salary)
                                     * 12 (= Yearly Salary)   */

    return (code, first + " " + last, hourSalary * 8 * 5 * 4 * 12);
}

Other Topics on Tuples

Omitting a Tuple Name

In our introduction to variables, we saw that you can declare many variables in one statement. You provide one data type for the variables and those variables must be same type. You can optionally initialize each variable. Here is an example:

using static System.Console;

int number = 927_594;
string first = "Michael", last = "Carlock";
double sal = 28.23;

WriteLine("Employee Record");
WriteLine("--------------------------------");
WriteLine("Employee #:     {0}", number);
WriteLine("Employee Name:  {0} {1}", first, last);
WriteLine("Hourly Salary:  {0}", sal);
WriteLine("================================");

This would produce:

Employee Record
--------------------------------
Employee #:     927594
Employee Name:  Michael Carlock
Hourly Salary:  28.23
================================
Press any key to continue . . .

In previous sections of this lesson, we saw that you can declare a tuple variable, give it a name, and provide a value for each of its items. Here is an example:

using static System.Console;

(int number, string first, string last, double sal) staff = (927_594, "Michael", "Carlock", 28.23);

WriteLine("Employee Record");
WriteLine("--------------------------------");
WriteLine("Employee #:     {0}", staff.number);
WriteLine("Employee Name:  {0} {1}", staff.first, staff.last);
WriteLine("Hourly Salary:  {0}", staff.sal);
WriteLine("================================");

The name of a tuple variable is necessary only if you are planning to use for a specific reason. Otherwise, in most cases, you can create a tuple without giving it a name. If you omit the name of the tuple, you can access each name of the items where you need it. Here is an example:

using static System.Console;

(int number, string first, string last, double sal) = (927_594, "Michael", "Carlock", 28.23);

WriteLine("Employee Record");
WriteLine("--------------------------------");
WriteLine("Employee #:     {0}", number);
WriteLine("Employee Name:  {0} {1}", first, last);
WriteLine("Hourly Salary:  {0}", sal);
WriteLine("================================");

A a result, a tuple solves the problem of declaring many variable with one statement. The variables can be of different types and you don't have to name the tuple variable.

Practical LearningPractical Learning: Passing a Tuple as Argument

  1. Change the PayrollProcessing.cs document as follows:
    using static System.Console;
    
    PreparePayroll();
    
    // -------------------------------------------------------
    
    (string fn, string ln, double sal) IdentifyEmployee()
    {
        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 first = ReadLine();
        Write("Last Name:     ");
        string last = ReadLine();
        Write("Hourly Salary: ");
        double wages = double.Parse(ReadLine());
    
        return (first, last, wages);
    }
    
    (double m, double t, double w, double h, double f) GetTimeWorked()
    {
        WriteLine("-------------------------------------------------------");
        WriteLine("Time worked");
        WriteLine("-------------------------------------------------------");
        Write("Monday:        ");
        double mon = double.Parse(ReadLine());
        Write("Tuesday:       ");
        double tue = double.Parse(ReadLine());
        Write("Wednesday:     ");
        double wed = double.Parse(ReadLine());
        Write("Thursday:      ");
        double thu = double.Parse(ReadLine());
        Write("Friday:        ");
        double fri = double.Parse(ReadLine());
        
        return (mon, tue, wed, thu, fri);
    }
    
    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 rt, double rp, double ov, double op) EvaluateSalary(double sal, double time)
    {
        double regTime = time;
        double regPay = sal * time;
        double overtime = 0.00;
        double overPay = 0.00;
    
        if (time is > 40.00)
        {
            regTime = 40.00;
            regPay = sal * 40.00;
            overtime = time - 40.00;
            overPay = sal * 1.50 * overtime;
        }
    
        return (regTime, regPay, overtime, overPay);
    }
    
    void PreparePayroll()
    {
        (string firstName, string lastName, double salary) staff = IdentifyEmployee();
        (double monday, double tuesday, 
         double wednesday, double thursday, double friday) time = GetTimeWorked();
    
        double timeWorked = Add5(time.monday, time.tuesday, time.wednesday, time.thursday, time.friday);
        
        (double regularTime, double regularPay,
         double overtime, double overtimePay) pay = EvaluateSalary(staff.salary, timeWorked);
    
        double weeklyPay = Add2(pay.regularPay, pay.overtimePay);
    
        WriteLine("=======================================================");
        WriteLine("FUN DEPARTMENT STORE");
        WriteLine("=======================================================");
        WriteLine("Payroll Evaluation");
        WriteLine("=======================================================");
        WriteLine("Employee Information");
        WriteLine("-------------------------------------------------------");
        WriteLine($"Full Name:     {staff.firstName} {staff.lastName}");
        WriteLine($"Hourly Salary: {staff.salary:f}");
        WriteLine("=======================================================");
        WriteLine("Time Worked Summary");
        WriteLine("--------+---------+-----------+----------+-------------");
        WriteLine(" Monday | Tuesday | Wednesday | Thursday | Friday");
        WriteLine("--------+---------+-----------+----------+-------------");
        WriteLine($"  {time.monday:f}  |   {time.tuesday:f}  |    {time.wednesday:f}   |   {time.thursday:f}   |  {time.friday:f}");
        WriteLine("========+=========+===========+==========+=============");
        WriteLine("                                    Pay Summary");
        WriteLine("-------------------------------------------------------");
        WriteLine("                                   Time   Pay");
        WriteLine("-------------------------------------------------------");
        WriteLine($"                     Regular:    {pay.regularTime:f}   {pay.regularPay:f}");
        WriteLine("-------------------------------------------------------");
        WriteLine($"                     Overtime:    {pay.overtime:f}   {pay.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:    Laura
    Last Name:     Glasgow
    Hourly Salary: 34.17
    -------------------------------------------------------
    Time worked
    -------------------------------------------------------
    Monday:        8
    Tuesday:       10
    Wednesday:     8.5
    Thursday:      10.5
    Friday:        9.5
    =======================================================
    FUN DEPARTMENT STORE
    =======================================================
    Payroll Evaluation
    =======================================================
    Employee Information
    -------------------------------------------------------
    Full Name:     Laura Glasgow
    Hourly Salary: 34.17
    =======================================================
    Time Worked Summary
    --------+---------+-----------+----------+-------------
     Monday | Tuesday | Wednesday | Thursday | Friday
    --------+---------+-----------+----------+-------------
      8.00  |   10.00  |    8.50   |   10.50   |  9.50
    ========+=========+===========+==========+=============
                                        Pay Summary
    -------------------------------------------------------
                                       Time   Pay
    -------------------------------------------------------
                         Regular:    40.00   1366.80
    -------------------------------------------------------
                         Overtime:    6.50   333.16
    =======================================================
                         Net Pay:            1699.96
    =======================================================
    
    Press any key to close this window . . .
  4. Return to your programming environment
  5. Remember that you can omit the name the tuple variable if you don't need it. For some examples, change the code as follows:
    using static System.Console;
    
    PreparePayroll();
    
    // -------------------------------------------------------
    
    . . .
    
    void PreparePayroll()
    {
        (string firstName, string lastName, double salary) = IdentifyEmployee();
        (double monday, double tuesday, 
         double wednesday, double thursday, double friday) = GetTimeWorked();
    
        double timeWorked = Add5(monday, tuesday, wednesday, thursday, friday);
        
        (double regularTime, double regularPay,
         double overtime, double overtimePay) = EvaluateSalary(salary, timeWorked);
    
        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: {salary:f}");
        WriteLine("=======================================================");
        WriteLine("Time Worked Summary");
        WriteLine("--------+---------+-----------+----------+-------------");
        WriteLine(" Monday | Tuesday | Wednesday | Thursday | Friday");
        WriteLine("--------+---------+-----------+----------+-------------");
        Write($"  {monday:f}  |   ");
        Write($"{tuesday:f}  |    ");
        Write($"{wednesday:f}   |   ");
        Write($"{thursday:f}   |  ");
        WriteLine($"{friday: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("=======================================================");
    }
  6. To execute, press Ctrl + F5
  7. Type some values and press Enter after each value:
    FUN DEPARTMENT STORE
    =======================================================
    Payroll Preparation
    -------------------------------------------------------
    Enter the following pieces of information
    -------------------------------------------------------
    Employee Information
    -------------------------------------------------------
    First Name:    Richard
    Last Name:     Stones
    Hourly Salary: 18.86
    -------------------------------------------------------
    Time worked
    -------------------------------------------------------
    Monday:        8
    Tuesday:       6.5
    Wednesday:     7
    Thursday:      9
    Friday:        6
    =======================================================
    FUN DEPARTMENT STORE
    =======================================================
    Payroll Evaluation
    =======================================================
    Employee Information
    -------------------------------------------------------
    Full Name:     Richard Stones
    Hourly Salary: 18.86
    =======================================================
    Time Worked Summary
    --------+---------+-----------+----------+-------------
     Monday | Tuesday | Wednesday | Thursday | Friday
    --------+---------+-----------+----------+-------------
      8.00  |   6.50  |    7.00   |   9.00   |  6.00
    ========+=========+===========+==========+=============
                                        Pay Summary
    -------------------------------------------------------
                                       Time   Pay
    -------------------------------------------------------
                         Regular:    36.50   688.39
    -------------------------------------------------------
                         Overtime:    0.00   0.00
    =======================================================
                         Net Pay:            688.39
    =======================================================
        
    Press any key to close this window . . .
  8. Return to your programming environment

Discarding Tuples Items

If you have a function that returns a tuple, we now know how to get the tuple returned by the function, access each item in that tuple and use it as you see fit. Here is an example:

using static System.Console;

(int number, string name, string status, double salary) = Summarize();

WriteLine("Employee Record");
WriteLine("----------------------------------");
WriteLine("Employee #:        {0}", number);
WriteLine("Employee Name:     {0}", name);
WriteLine("Employment Status: {0}", status);
WriteLine("Yearly Salary:     {0:n}", salary);
WriteLine("==================================");

(int, string, string, double) Summarize()
{
    string stt = "Part Time";
    double hourSalary = 22.86;
    int code = 293_704;
    string first = "James", last = "Warfield";

    /* Yearly Salary = Hourly Salary *  8 (= Daily Salary)
                                     *  5 (= Weekly Salary)
                                     *  4 (= Monthly Salary)
                                     * 12 (= Yearly Salary)   */

    return (code, first + " " + last, stt, hourSalary * 8 * 5 * 4 * 12);
}

This would produce:

Employee Record
----------------------------------
Employee #:        293704
Employee Name:     James Warfield
Employment Status: Part Time
Yearly Salary:     43,891.20
==================================

Press any key to close this window . . .

Even if a function returns a tuple, when you call that funtion, in some cases, you are not planning to use all the values in the returned tuple. You can indicate to the compiler the only items you are planning to use from the returned tuple. To do that, in the tuple variable to which you are assigning the function, create a placeholder for each item. For the item you will use, specify its name. For the item you will not use, in its placeholder, type an underscore. Here is an example:

using static System.Console;

(_, string name, _, double salary) = Summarize();

WriteLine("==================================");
WriteLine("Employee Record");
WriteLine("----------------------------------");
WriteLine("Employee Name: {0}", name);
WriteLine("Yearly Salary: {0:n}", salary);
WriteLine("==================================");

(int, string, string, double) Summarize()
{
    WriteLine("Enter information about the employee");
    Write("Emloyee #: ");
    int number = int.Parse(ReadLine());
    Write("Full Name: ");
    string name = ReadLine();
    WriteLine("----------------------------------");
    WriteLine("Employment Status: ");
    WriteLine("1. Full Time");
    WriteLine("2. Part Time");
    WriteLine("3. Contractual");
    WriteLine("4. Seasonal");
    Write("Enter status (1, 2, 3, or 4): ");
    string stt = ReadLine();
    WriteLine("----------------------------------");

    stringemplStatus = "Unknown";

    if(stt == "1")
        emplStatus = "Full Time";
    else if (stt == "2")
        emplStatus = "Part_Time";
    else if (stt == "3")
        emplStatus = "Contractual";
    else if (stt == "4")
        emplStatus = "Seasonal";

    Write("Hourly Salary: ");
    double sal = double.Parse(ReadLine());

    return (number, name, emplStatus, sal * 8 * 5 * 4 * 12);
}

Here is an example of running the program:

Enter information about the employee
Emloyee #: 39874
Full Name: Catherine Donfack
----------------------------------
Employment Status:
1. Full Time
2. Part Time
3. Contractual
4. Seasonal
Enter status (1, 2, 3, or 4): 2
----------------------------------
Hourly Salary: 32.27
==================================
Employee Record
----------------------------------
Employee Name: Catherine Donfack
Yearly Salary: 61,958.40
==================================

Press any key to close this window . . .

Combining Tuples in Declaring Tuple Variables

We have already seen how to create a tuple. Here is an example:

(string, int, string, double) pay_scale) contractor;

In reality, every element of a tuple is an entity of its own. This means that you can create a tuple where an element of a tuple would be. Here are examples of tuples included in a tuple:

((string, string), int, (int, int, int), bool, (string, double)) contractor;

If the creation of a tuple is very long, you can create the element on different lines, like this:

((string, string),
     int, 
     (int, int, int),
     bool,
     (string, double)
    ) contractor;

Or like this:

(
    (string, string),
     int,
      (int, int, int),
       bool,
      (string, double)
    ) contractor;

In fact, the following notation works as well:

(
    (
      	string,
        string
    ),
    int,
        (
         int,
         int,
         int
        ),
     bool,
     (
      	string,
        double
     )
) contractor;

Once again, you are not required to name the elements of the tuples, but you must admit that the above tuple can be difficult to read. First, you must identify the primary element and how many they are. If you don't name them, the incremental default names given to them are Item1, Item2, etc.

To access an element that is from an internal tuple, first access its parent position.. This can be done as follows:

Tuples and Properties

Then use a period to access the internal element. This can be done as follows:

Tuples and Properties

As you can see, to make your tuple easy to read, it may be a good idea to name it elements. If you want, you can name just the primary elements. Here is an example:

((string, string) full_name, double height, (int, int, int) date_hired, bool recommended, (string, double) pay_scale) contractor;

On the other hand, you can name only the internal elements. Here are examples:

((string fname, string lname), double, (int month, int day, int year), bool, (string status, double rate)) contractor;

Otherwise, you can, and should, name all elements, primary and internal. Here are examples:

(
  (string fname, string lname) full_name,
  (int month, int day, int year) date_hired,
  (string status, double rate) pay_scale
) contractor;

You can then conveniently access the tuples and their elements using their explicit names. Here is an example:

(
    (string fname, string lname) full_name,
    double hourly_salary, 
    (int month, int day, int year) date_hired,
    bool is_full_time, 
    (string status, int rate) pay_scale
) contractor;

// Accessing items individually
contractor.hourly_salary    = 22.85;
contractor.full_name.fname  = "Peter";
contractor.full_name.lname  = "Jacobson";
contractor.date_hired.month = 4;
contractor.date_hired.day   = 18;
contractor.date_hired.year  = 2022;
contractor.is_full_time     = true;
contractor.pay_scale.status = "Full-Time";
contractor.pay_scale.rate   = 3;

// Accessing items individual tuples
contractor.full_name = ("Jennifer", "Sopngui");
contractor.date_hired = (10, 6, 2022);
contractor.hourly_salary = 14.05;
contractor.is_full_time = true;
contractor.pay_scale = ("Part-Time", 1);

// Accessing the whole tuple
contractor = (("Paul", "Chancellor"), 27.96, (07, 02,2022), true, ("Unknown", 2));

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2025, FunctionX Sunday 21 January 2024 Next