Fundamentals of Tuples

Introduction

A tuple is a series of values considered as an entity. A tuple is not a data type like an integer or a string, but it is used as if it were. This means that you can declare a variable as a tuple but it is not strictly used as the types of regular variables we have used so far.

A tuple is a combination of values where each value is recognized for itself. A value can be one of the primitive types we have already seen (int, bool, double, or string).

Practical LearningPractical Learning: Introducing Tuples

  1. Start Microsoft Visual Studio
  2. Create a new Console App named PayrollPreparation5 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(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

Creating a Tuple

You create a tuple as if you are declaring a variable as we have done so far. As a reminder, the formula to declare a variable is:

data-type variable-name;

This time, in place of the data type, use some parentheses. For what inside the parentheses, you have various options. To start, in the parentheses of the tuple, you can write two or more data types. Those data types are separated by commas. Here are examples:

// A tuple made of integral numbers only
(int, int)
// A tuple made of strings only
(string, string, string)
// A tuple made of various types of values
(int, string, double)

A value in a tuple can be called an item, a member, or an element (those are the names we will use in our lessons; all those names will mean the same thing).

In some cases, you can use an algebraic name to identify or define a tuple:

Naming a Tuple

After specifying the type of the tuple, like every variable, you must name it. This is done after the closing parenthesis. The name of a tuple follows the names of variables. After the name of the variable, add a semicolon. Here are examples:

(int, int) coordinates;
(string, string, string) employeeName;
(int, string, double) definition;

Initializing a Tuple: Binding Values to Elements of a Tuple

As is the case for other variables, before using a variable, it must have (a) value(s). This can be done by assigning a value to each member of the tuple. You have various options.

As one way to initialize a tuple, assign the desired values to it. As a reminder, the formula to declare and initialize a variable is:

data-type variable-name = value;

Based on this formula, to initialize a tuple, add the assignment operator after the name of the tuple. Add some parentheses. In the parentheses, specify the value of each member exactly in the order the data types appear in the declaration. Here is an example:

(string, string, string) students = ("Aaron", "Jennifer", "Yerimah");

As an alternative, you can first declare a variable on one line, and assign the desired values on another line. Here is an example:

(string, string, string) students;

students = ("Aaron", "Jennifer", "Yerimah")

Introduction to Using a Tuple

Introduction

The primary way you can use a tuple is to present its values to the user. To do this from the Write() or the WriteLine() methods, enter the name of the tuple in the parentheses. Here is an example:

using static System.Console;

(string, string) employee = ("Robert", "Ewell");

Write("Employee: ");
WriteLine(employee);
WriteLine("=================================");

This would produce:

Employee: (Robert, Ewell)
=================================
Press any key to continue . . .

Accessing an Element of a Tuple

The elements of a tuple each has a name. By default, the first element is named Item1, the second element is named Item2, and so on. These names are specified automatically by the compiler when you create a tuple. To access an element of a tuple, type the variable name of a tuple, a period, and the name of the element. If you are using Microsoft Visual Studio to develop your application, when you type the tuple variable and a period, the intellisense will display the names of the elements of the tuple. Here is an example:

Accessing an Element of a Tuple

By accessing each element like that, you can initialize a tuple by assigning a value to each element. Here is an example:

(int, string, string, double) contractor;

contractor.Item1 = 947_069;
contractor.Item2 = "Gerard";
contractor.Item3 = "Soundjok";
contractor.Item4 = 68426;

In the same way, you can access an element to present its value to the user. Here are examples:

using static System.Console;

(int, string, string, double) contractor;

contractor.Item1 = 947_069;
contractor.Item2 = "Gerard";
contractor.Item3 = "Soundjok";
contractor.Item4 = 68426;

WriteLine("Employee Record");
WriteLine("------------------------");
Write("Employee #:    ");
WriteLine(contractor.Item1);
Write("First Name:    ");
WriteLine(contractor.Item2);
Write("Last Name:     ");
WriteLine(contractor.Item3);
Write("Yearly Salary: ");
WriteLine(contractor.Item4);
WriteLine("========================");

This would produce:

Employee Record
------------------------
Employee #:    947069
First Name:    Gerard
Last Name:     Soundjok
Yearly Salary: 68426
========================
Press any key to continue . . .

Naming the Members of a Tuple

As seen already, when creating a tuple, you can simply specify the data types of the members of the tuple. As an option, you can name 0, some, or all members of the tuple. To name a member, after the data type of a member, add a space and a name. Again, you are free to choose what member(s) to name. Here are examples:

(double, string) x;
(int horizontal, int) coordinates;
(string first_name, string, string last_name) employeeName;
(int employeeNumber, string employment_Status, double yearlysalary) definition;

You can then initialize the tuple. Once again, to access an element of a tuple, type the name of the tuple variable, a period, and the element you want. Again, if you are using Microsoft Visual Studio, the intellisense will display the names of the elements of the tuple. Here are two examples where some elements were named and some were not:

Accessing an Element of a Tuple

Accessing an Element of a Tuple

When accessing the items of a tuple, if you had named an element, you can use either its default name (Item1, Item2, etc) or the name you had specified.

Other Techniques of Initializing a Tuple

A Value from a Variable

We already know that, when you create a tuple, sooner or later, you must specify the value of each member. The value of a member can come from a variable. Here is an example:

using static System.Console;

int emplNbr = 138_475;

(int emplNumber, string firstName, string lastName) employee = (emplNbr, "Gwendolyn", "Valance");

WriteLine("Employee Record");
WriteLine("---------------------------------------");
WriteLine($"Employee #: {employee.emplNumber}");
WriteLine($"Full Name:  {employee.Item2} {employee.lastName}");
WriteLine("=======================================");

This would produce:

Employee Record
---------------------------------------
Employee #: 138475
Full Name:  Gwendolyn Valance
=======================================
Press any key to continue . . .

A Tuple Item from an Expression

The value of a member of a tuple can come from an expression. Here is an example:

using static System.Console;

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

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

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

A var Tuple

You can declare a tuple variable using the var keyword. Remember that if you declare a variable with that keyword, you must immediately initialize it. Therefore, the formula to declare a var tuple is:

var variable-name = ( item_1, item_2, item_x);

In the parentheses, you can specify the desired value for each member of the tuple. Here is an example:

var staff = (392507, "Gertrude", "Ngovayang", 96275);

You can then access the elements of the tuple. Once again in this case, by default, the first element is named Item1, the second is name Item2, and so on. Here are examples:

using static System.Console;

var staff = (392507, "Gertrude", "Ngovayang", 96275);

WriteLine("Employee Record");
WriteLine("------------------------");
Write("Employee #:    ");
WriteLine(staff.Item1);
Write("First Name:    ");
WriteLine(staff.Item2);
Write("Last Name:     ");
WriteLine(staff.Item3);
Write("Yearly Salary: ");
WriteLine(staff.Item4);
WriteLine("========================");

This would produce:

Employee Record
------------------------
Employee #:    392507
First Name:    Gertrude
Last Name:     Ngovayang
Yearly Salary: 96275
========================
Press any key to continue . . .

We saw that, when creating a tuple, you can specify the name of an element. If you are creating a var tuple, to specify the name of an element, in the parentheses, type that name, a colon, and the value of the element. Here are examples:

var staff = (392507, firstName: "Gertrude", "Ngovayang", salary: 96275);

This time too, you can access an element either by its ordinal name or the name you had given it, if any. Here are examples:

using static System.Console;

var staff = (emplNumber: 392507, "Gertrude", lastName: "Ngovayang", 96275, fullTime: true);

WriteLine("Employee Record");
WriteLine("------------------------------");
Write("Employee #:         ");
WriteLine(staff.Item1);
Write("First Name:         ");
WriteLine(staff.Item2);
Write("Last Name:          ");
WriteLine(staff.lastName);
Write("Yearly Salary:      ");
WriteLine(staff.Item4);
Write("Employed Full-Time: ");
WriteLine(staff.Item5);
WriteLine("=============================");

This would produce:

Employee Record
------------------------------
Employee #:         392507
First Name:         Gertrude
Last Name:          Ngovayang
Yearly Salary:      96275
Employed Full-Time: True
=============================
Press any key to continue . . .

Tuples and Conditional Statements

Introduction

A tuple is a series of values treated as an entity but where each item can be accessed on its own. Once you have accessed an item, you can perform a comparison on it. Here is an example:

using static System.Console;

(int memNbr, string name, string category, int fee) member;

member.memNbr = 938_405;
member.name     = "Matthew Groeder";
member.category = "Adult";
member.fee      = -1;

if (member.category == "Child")
    member.fee = 0;
if (member.category == "Yound Adult")
    member.fee = 15;
if (member.category == "Adult")
    member.fee = 45;
if (member.category == "Senior")
    member.fee = 25;

WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=");
WriteLine("Club Membership");
WriteLine("==============================================");
WriteLine("Member Information");
WriteLine("----------------------------------------------");
WriteLine($"Membership #:    {member.memNbr}");
WriteLine($"Member Name:     {member.name}");
WriteLine($"Membership Type: {member.category}");
WriteLine("----------------------------------------------");
WriteLine($"Membership Fee:  ${member.fee}");
WriteLine("==============================================");

This would produce:

+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
Club Membership
==============================================
Member Information
----------------------------------------------
Membership #:    938405
Member Name:     Matthew Groeder
Membership Type: Adult
----------------------------------------------
Membership Fee:  $45
==============================================

Press any key to close this window . . .

Comparing Tuples

So far, we have used tuples made of primitive values (there can be other types of values in a tuple). In the C# language (actually in the .NET Framework), each type of those values is configured to be compared to equality or difference with another value of the same type. Thanks to this characteristic, you can compare two tuples to find out whether they are equal or different. Consider the following two tuples:

(int memNbr, string name, string category, int fee) member = (938_405, "Matthew Groeder", "Adult", 15);
(string category, int memNbr, int fee, string name) candidate = ("Adult", 938_405, 15, "Matthew Groeder");

Notice that these two tuples have the same values but the orders of those values are different from the first to the second tuple. As a result, you cannot compare these two tuples.

Before comparing two tuples, both tuples should have the same types of values in the same orders. You can then compare such tuples for equality or difference. When you do that, the compiler will compare the value of the item in the first tuple to the value of the item in the same position of the second tuple. If both values are the same, the compiler would move to the next item. If the item in a tuple holds the same value as the item in the same position in the other tuple, and this is applied to all items in the tuples, the compiler would conclude that both tuples are equal. If at least one item in a tuple is different from the item in the same position of the other tuple, even if the other items are the same, the compiler would conclude that those tuples are different. Consider the following example:

using static System.Console;

// One tuple
(int memNbr, string name, string category, int fee) member    = (938_405, "Matthew Groeder", "Adult", 15);
// Another tuple
(int memNbr, string name, string category, int fee) person    = (938_405, "Matthew Groeder", "Adult", 15);
// One more tuple
(int memNbr, string name, string category, int fee) candidate = (938_405, "Stephen Gerber",  "Adult", 15);

WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=");
WriteLine("Club Membership");
WriteLine("==============================================");
WriteLine("Member Information");
WriteLine("----------------------------------------------");
WriteLine($"Membership #:    {member.memNbr}");
WriteLine($"Member Name:     {member.name}");
WriteLine($"Membership Type: {member.category}");
WriteLine($"Membership Fee:  ${member.fee}");
WriteLine("==============================================");
WriteLine("Member Information");
WriteLine("----------------------------------------------");
WriteLine($"Membership #:    {person.memNbr}");
WriteLine($"Member Name:     {person.name}");
WriteLine($"Membership Type: {person.category}");
WriteLine($"Membership Fee:  ${person.fee}");
WriteLine("==============================================");
WriteLine("Member Information");
WriteLine("----------------------------------------------");
WriteLine($"Membership #:    {candidate.memNbr}");
WriteLine($"Member Name:     {candidate.name}");
WriteLine($"Membership Type: {candidate.category}");
WriteLine($"Membership Fee:  ${candidate.fee}");
WriteLine("==============================================");

if (member == person)
    WriteLine("The members are the same.");
else
    WriteLine("People are different.");

WriteLine("----------------------------------------------");

if (member == candidate)
    WriteLine("Both people are different.");
else
    WriteLine("People are different.");

This would produce:

+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
Club Membership
==============================================
Member Information
----------------------------------------------
Membership #:    938405
Member Name:     Matthew Groeder
Membership Type: Adult
Membership Fee:  $15
==============================================
Member Information
----------------------------------------------
Membership #:    938405
Member Name:     Matthew Groeder
Membership Type: Adult
Membership Fee:  $15
==============================================
Member Information
----------------------------------------------
Membership #:    938405
Member Name:     Stephen Gerber
Membership Type: Adult
Membership Fee:  $15
==============================================
The members are the same.
----------------------------------------------
People are different.

Press any key to close this window . . .

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

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-2024, FunctionX Sunday 21 January 2024 Next