A Class in a Tuple

Introduction

We saw how to declare tuple variables. In the same way, you can declare a tuple variable in the body of a class, in which case the variable is treated as a field. Here is an example:

public class Processor
{
    /* We are combining these pieces of information of the 
     * processor because processors specifications are 
     * related by generation and tied to a manufacturer. */
    (string make, string model) identification;
}

The Constructors of a Class

As you may know already, a constructor is a special method that is used to initialize an object. Therefore, if you create a regular tuple field, you can use a constructor to initialize it. Here is an example:

public class Processor
{
    /* We are combining these pieces of information of the 
     * processor because processors specifications are 
     * related by generation and tied to a manufacturer. */
    (string make, string model) identification;
    
    public Processor()
    {
    	identification = ("HP", "XL2X0 GEN9 E5-2620V3");
    }
}

A Read-Only Tuple

You can create a constant tuple but whose value depends on specific objects. This is the case for a read-only tuple. You can create it in the body of a class and initialize it in a constructor. Here is an example:

public class Memory
{
    public readonly (int numberOfSockets, int memoryInGB) partition;

    public Memory()
    {
        partition = (2, 8);
    }

    public Memory(int capacity)
    {
        partition = (2, 16);
    }
}

Methods and Tuples

We saw how to involve tuples with functions. Everything we saw about passing a tuple as argument and returning a tuple can be applied exactly the same way to the methods of a class. Normally, methods deal with tuples exactly as we described for functions, with just minor adjustments. It is important to remember (as stated in our introductory lesson on functions) that a function is section of code behaves as if it written outside of a class. Otherwise, everything we studied about involving tuples and functions also applied to methods. This means that you can pass a tuple to a method and you can return a tuple from a method.

As you know already, a method is a function created inside a class. As you know already, if you create a method, it has direct access to other members of the same class. Therefore, if you create a field or a property that is a tuple, you can use that member in the method. In a method, you have direct access to the names of the tuples. To access an element of a tuple, type the name of the member, a period, and the desired member. That way, you can initialize a tuple. Here is an example:

public class Processor
{
    /* We are combining these pieces of information of the 
     * processor because processors specifications are 
     * related by generation and tied to a manufacturer. */
    private (string make, string model, string socket) identification;

    private void Create()
    {
        identification = ("AMD", "RYZEN 5", "AM4");
    }
}

An Object in a Tuple

All the elements we used so far in tuples were of regular types. In reality, each element is a placeholder for practically any type you want. Based on this, an element of a tuple can be an object of a structure or class type. Of course, you must have a class. You can create and use your own class. Here is an example of a class named Trapezoid created in a Windows Forms application named Geometry:

namespace Geometry
{
    public class Trapezoid
    {
        public double TopBase    { get; set; }
        public double BottomBase { get; set; }
        public double Height     { get; set; }

        public double Area
        {
            get
            {
                return Height * (TopBase + BottomBase) / 2.00;
            }
        }
    }
}

When creating the tuple, specify the desired element using the name of the class. Here is an example:

using System;
using System.Windows.Forms;

namespace Geometry
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            Trapezoid isosceles = new Circle();

            (Trapezoid shape, int value) definition;
        }
    }
    
    class Trapezoid
    {
    }
}

When initializing the tuple or when specifying its value, you must define the object used as element. You have various options:

In the above example, we used a tuple that has one elment that is a class type. In the same way, you can create a tuple withe more than one element that are of class or structure type. The elements can be of the same class (or structure) or different classes (or structures).

In the above example, we used our own class. On the other hand, we know that the .NET Framework provides a large collection of classes and structures. You can use any of most of the many classes of the .NET Framework for an element of a tuple.

Tuples and Properties

Introduction

The data type of a property can be a tuple type. When creating the tuple, there is nothing magical: simply create a tuple in place of the data type. Here is an example:

public class Employee
{
    public (int, string, bool) Identification;
}

As seen in our introduction to properties, if you want to control the details of processing a property, you can create a private field that is the same tuple type as the property. Then add either or both a get and a set clauses. Here is an example:

public class Employee
{
    private (int, string, bool) id;

    public (int, string, bool) Identification
    {
        get
        {
            return id;
        }
        set
        {
            id = value;
        }
    }
}

An Automatic Tuple Property

If you are not planning to validate, accept, or reject the values of the property, you can create the property as an automatic one. Here is an example:

public enum PayFrequency { Daily, Monthly, Yearly }

public class Employee
{
    private (int, string, bool) id;

    public (int, string, bool) Identification
    {
        get
        {
            return id;
        }
        set
        {
            id = value;
        }
    }

    public (bool, string, PayFrequency, double) Salary { get; set; }
}

When creating the property, it is a good idea, although not a requirement, to name the elements of the tuple. It may also be a good idea to add comments that explain the roles of the elements of the tuple. Here is an example:

public enum PayFrequency { Daily, Monthly, Yearly }

public class Employee
{
    private (int, string, bool) id;

    /* An employee is identified with three pieces of information:
     * the code is a type of employee number or contractor code,
     * the name represents the full name. It could include the 
     *          first name, the middle initial, and a last name.
     * The last piece of information indicates whether the
     *          employee is part-time (false) or full-time (true). */
    public (int code, string name, bool full_time) Identification
    {
        get
        {
            return id;
        }
        set
        {
            id = value;
        }
    }

    /* We want various pieces of information that provide details about
     * employee or contractor's salary.
     * The isFixed item indicates whether an employee can work overtime
     *             (and get paid the hourly salary and half).
     * The Pay Frequency indicates what the value of the salary
     *             represents, such as hourly, monthly, etc.
     * The last value is the actual salary. Again, that value depends 
     *             on the pay frequency. */
    public (bool isFixed, PayFrequency often, double number) Salary { get; set; }
}

As mentioned earlier, if you don't name the elements of a tuple, the compiler gives them some default names as Item1, Item2, etc.

When using the property, you may need to access the elements of its type. You will access them by their names. From inside the class, such as in the body of a clause of another property or in the body of a method of the same name, type the name of the desired property, type a period, and select the element of your choice. Here are examples:

Tuples and Properties

Tuples and Properties

When using the property outside the class, if you have declared a variable of the class that owns the property, type the name of the object, a period, the name of the property, a period, and the desired element. Here is an example:

Tuples and Properties

Once you have accessed the property or any of its elements, you can use it like any property as we have done in previous lessons.

If you create an automatic tuple property, you cannot individually initialize the elements of the tuple property. Still, you can access the elements to present to the user. Here is an example:

using static System.Console;

public class Processor
{
    /* We are combining these pieces of information of the 
     * processor because processors specifications are 
     * related by generation and tied to a manufacturer. */
    public (string make, string model, string socket) Manufacture { get; set; }

    public (int, int) Count { get; set; }
    public double Speed { get; set; }

    public Processor()
    {
        Count = (6, 12);
        Manufacture = ("AMD", "RYZEN 5", "AM4");

        Present();
    }

    private void Present()
    {
        Write("Make:      ");
        WriteLine(Manufacture.make);
        Write("Model:     ");
        WriteLine(Manufacture.model);
        Write("Socket:    ");
        WriteLine(Manufacture.socket);
        Write("Processor: ");
        Write(Count.Item1);
        Write("-Core, ");
        Write(Count.Item2);
        WriteLine("-Thread.");
        WriteLine("==============================");
    }
}

public class Exercise
{
    public static void Main()
    {
        Processor proc = new Processor();
    }
}

This would produce:

Make:      AMD
Model:     RYZEN 5
Socket:    AM4
Processor: 6-Core, 12-Thread.
==============================
Press any key to continue . . .

Previous Copyright © 2001-2021, C# Key Next