Way to Return Multiple Values or What Are Tuples in .Net.

A long time ago, in .NET 4.0, tuples were introduced. It took a lot of time when I realized the true power of tuples. At first look at them, you can decide that tuples don`t worth your attention or even usage in production code. I want to show you a way how to leverage the best from tuples.

Tuples vs DTO

What are Tuples?

The tuples feature provides concise syntax to group multiple data elements in a lightweight data structure.

It was designed to be an analog data transfer object (DTO) and simplify code, making it clear and readable.

Even the sharpest sword is worth nothing in the wrong hands.

It`s better to avoid a situation when we can misuse tuples.

Let’s take a look at the next example of basic tuples usage:

1
2
3
4
5
6
7
8
9
10
// tuples values are not named!
(int, string) notNamedTuple = (1, "test");

Console.WriteLine(example.Item1);
Console.WriteLine(example.Item2);

// Too many tuple values
(int, string, int, string, int, string, bool, bool, int) tooLongExample = (1, "test", 2 , "anohter", 3, "again", false, true, 1);

Console.WriteLine(tooLongExample.Item9);

It is always a bad idea to rely on default values in case of tuples default names like a nightmare for future maintenance. Item1, Item2 — say nothing about real purpose and data which they contain.

Another not-so-good case is when you store a lot much information in Tuple. It is better to review your approach. I can agree that sometimes it`s required to store much-related information, and in such a case, I suggest thinking about DTO class usage.

As a result of DTO usage as developers, we create a lot of classes just to pass some data from one method to another. And here I would suggest using tuples. Instead of creating a new DTO class, Tuple with named properties could be used.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// ResultDto.cs
class ResultDto
{
public string String { get; set; }
public int Number { get; set; }
}

// Usage
public ResultDto TestDto()
{
return new ResultDto { Number = 1, String = "test"};
}

//
var result = TestDto();
Console.WriteLine(result.Number);

The example above could be written with tuples:

1
2
3
4
5
6
7
8
9
// Tuple return type
public (int Number, string String) TestTuple()
{
return (1, "test");
}

// Usage
var result = TestTuple();
Console.WriteLine(result.Number);

As you see, usage examples are the same. In the second example with tuples, we don`t need to maintain the additional class in our solution, and the code still works and stays readable.

Conclusion

If you didn`t use tuples in your coding, I hope this article encourages you to do it. No need to worry about unit testing; tuples support comparison by values, and you still can write simple assertions with them.