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

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

Tuples and Functions

A Value from a Function

Earlier, we saw that you can create a function that returns a value, you can call that function and assign its return value to a variable, then use that variable as an item of a tuple. Here is the example we used:

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 package 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 Method

We saw that you can pass a tuple to a method. 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 or method that takes more than one tuple as parameters.

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()
{

}

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 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);
}

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));

Previous Copyright © 2001-2023, C# Key Saturday 29 April 2023 Next