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

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

Referenced Tuple

As seen with other types, you can create and use a reference of a tuple. To proceed, first crate a tuple of your choice. Here is an example we saw earlier:

using static System.Console;

(int nbr, string fn, string ln, double sal) staff = (493_724, "Annette", "Wald", 44_444);

WriteLine("Staff Member");
WriteLine("------------------------");
Write("Employee #:    ");
WriteLine(staff.nbr);
Write("First Name:    ");
WriteLine(staff.fn);
Write("Last Name:     ");
WriteLine(staff.ln);
Write("Yearly Salary: ");
WriteLine(staff.sal);
WriteLine("========================");

This would produce:

Staff Member
------------------------
Employee #:    493724
First Name:    Annette
Last Name:     Wald
Yearly Salary: 44444
========================

Press any key to close this window . . .

To create a reference of a tuple, decalre a new variable that has the same types and order of items. Start the new variable with the ref keyword and assign the original variable to the new one. The variable you are assigning mus also start with the ref keyword. From that time, both the original and the new variable would have the same values. This can be verified as follows:

using static System.Console;

(int nbr, string fn, string ln, double sal) staff = (493_724, "Annette", "Wald", 44_444);

ref (int emplNumber, string firstName, string lastName, double salary) employee = ref staff;

WriteLine("Staff Member");
WriteLine("------------------------");
Write("Employee #:    ");
WriteLine(staff.nbr);
Write("First Name:    ");
WriteLine(staff.fn);
Write("Last Name:     ");
WriteLine(staff.ln);
Write("Yearly Salary: ");
WriteLine(staff.sal);
WriteLine("========================");

WriteLine("Employee Record");
WriteLine("------------------------");
Write("Employee #:    ");
WriteLine(employee.emplNumber);
Write("First Name:    ");
WriteLine(employee.firstName);
Write("Last Name:     ");
WriteLine(employee.lastName);
Write("Yearly Salary: ");
WriteLine(employee.salary);
WriteLine("========================");

This would produce:

Staff Member
------------------------
Employee #:    493724
First Name:    Annette
Last Name:     Wald
Yearly Salary: 44444
========================
Employee Record
------------------------
Employee #:    493724
First Name:    Annette
Last Name:     Wald
Yearly Salary: 44444
========================

Press any key to close this window . . .

After creating a referenced tuple, you can change the value of an item of either the original or the referenced variable. The changed value on the item would apply to the same item on the original or the referenced tuple. Consider the following example:

using static System.Console;

(int nbr, string fn, string ln, double sal) staff = (493_724, "Annette", "Wald", 44_444);

ref (int emplNumber, string firstName, string lastName, double salary) employee = ref staff;

WriteLine("Staff Member");
WriteLine("-----------------------------------------------------------");
Write("Employee #:    ");
WriteLine(staff.nbr);
Write("First Name:    ");
WriteLine(staff.fn);
Write("Last Name:     ");
WriteLine(staff.ln);
Write("Yearly Salary: ");
WriteLine(staff.sal);
WriteLine("===========================================================");

WriteLine("Employee Record");
WriteLine("-----------------------------------------------------------");
Write("Employee #:    ");
WriteLine(employee.emplNumber);
Write("First Name:    ");
WriteLine(employee.firstName);
Write("Last Name:     ");
WriteLine(employee.lastName);
Write("Yearly Salary: ");
WriteLine(employee.salary);
WriteLine("===========================================================");

// Updating a value on the original tuple
staff.fn = "George";
// Updating a value on the referenced tuple
employee.salary = 77_777;

WriteLine("After changing a value on other original or the reference...");

WriteLine("Staff Member");
WriteLine("-----------------------------------------------------------");
Write("Employee #:    ");
WriteLine(staff.nbr);
Write("First Name:    ");
WriteLine(staff.fn);
Write("Last Name:     ");
WriteLine(staff.ln);
Write("Yearly Salary: ");
WriteLine(staff.sal);
WriteLine("===========================================================");

WriteLine("Employee Record");
WriteLine("-----------------------------------------------------------");
Write("Employee #:    ");
WriteLine(employee.emplNumber);
Write("First Name:    ");
WriteLine(employee.firstName);
Write("Last Name:     ");
WriteLine(employee.lastName);
Write("Yearly Salary: ");
WriteLine(employee.salary);
WriteLine("===========================================================");

This would produce:

Staff Member
-----------------------------------------------------------
Employee #:    493724
First Name:    Annette
Last Name:     Wald
Yearly Salary: 44444
===========================================================
Employee Record
-----------------------------------------------------------
Employee #:    493724
First Name:    Annette
Last Name:     Wald
Yearly Salary: 44444
===========================================================
After changing a value on other original or the reference...
Staff Member
-----------------------------------------------------------
Employee #:    493724
First Name:    George
Last Name:     Wald
Yearly Salary: 77777
===========================================================
Employee Record
-----------------------------------------------------------
Employee #:    493724
First Name:    George
Last Name:     Wald
Yearly Salary: 77777
===========================================================

Press any key to close this window . . .

Notice that, in the above example, a value of the tuple can be changed on the referenced tuple. In some cases, you may want to prevent the referenced tuple from changing the value of any of the item of the original tuple. We already know that, to put that restriction, you can apply the readonly keyword to the referenced tuple variable. Consider the following code:

(int nbr, string fn, string ln, double sal) staff = (493_724, "Annette", "Wald", 44_444);

ref readonly (int emplNumber, string firstName, string lastName, double salary) employee = ref staff;

staff.fn = "George";
employee.salary = 77_777;

This code would produce an error because the variable is read-only.

Practical LearningPractical Learning: Ending the Lesson


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