Mastering Tuples in .NET

In .NET, a tuple is a lightweight data structure that allows you to group together multiple values of different types. They are particularly useful in scenarios where you need to return more than one value from a method or when you want to pass multiple values as a single argument to a method. Tuples can be defined using the Tuple class or by utilizing the shorthand notation introduced in C# 7.0.

The Tuple class facilitates the creation of tuples with a maximum of eight elements. On the other hand, the shorthand notation offers a concise syntax for creating tuples. To create a tuple representing a person’s name and age, for instance, you can use the following syntax:

var person = ("John", 35);

You can access the values in a tuple using the dot notation or by using deconstruction. With deconstruction, you can assign the tuple elements to individual variables, like this:

var (name, age) = person;

Tuples can be useful in situations where you need to group together multiple values without creating a custom class for that purpose. They can help to simplify code and make it more readable.

Example

Here is an example from my open-source project that utilizes a named tuple, which is preferable due to its enhanced readability.

public static ReadOnlyCollection<(string FileName, string ErrorMessage)>
  DeleteFiles(this IEnumerable<string> files)
{
	files = files.ArgumentNotNull();

	var errors = new List<(string FileName, string ErrorMessage)>();

	_ = Parallel.ForEach(source: files, body: (fileName) =>
	{
		try
		{
			if (File.Exists(fileName))
			{
				File.Delete(fileName);
			}
		}
		catch (Exception ex) when (ex is ArgumentException or
		  ArgumentNullException or
		  System.IO.DirectoryNotFoundException or
		  IOException or
		  NotSupportedException or
		  PathTooLongException or
		  UnauthorizedAccessException)
		{
			errors.Add((FileName: fileName, 
                   ErrorMessage: ex.GetAllMessages()));
		}
	});

	return errors.ToReadOnlyCollection();
}

Here is how to use this method:

var deletedFiles = FileHelper.DeleteFiles(files.Select(
                                           p => p.FullName));

foreach (var deletedFile in deletedFiles)
{
	Console.WriteLine($"FileName: {deletedFile.FileName}, 
                      Error: {deletedFile.ErrorMessage},");
}

As you can see, named tuples are very easy to use and read. However, it’s important not to overuse them. If you find yourself needing more than two or three values in the response, using a class or structure might be a better approach.

Tuples can be employed as method parameters, as illustrated in this example generated by ChatGPT:

static void DisplayPersonInfo((string Name, int Age, 
                               bool IsStudent) personTuple)
{
    // Accessing tuple elements using names
    string name = personTuple.Name;
    int age = personTuple.Age;
    bool isStudent = personTuple.IsStudent;

    // Displaying information
    Console.WriteLine($"Name: {name}, Age: {age}, Is Student: {isStudent}");
}

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.