Tuples with C# 7

C# 7 bring bunch of new features and we're going to talk about one of them: Tuples. Actually, Tuples already exist in C# since the .NET Framework 4 and it should be better to speak about an improvement rather than a really really new feature.

How to Use It

Typically, the benefits of Tuples allow you to create a structure with different types when it's impossible with an array (or you have to use an array of objects and it's not so good for the "type safety"). So you can return multiple values of different types within a method when it's impossible without to create a new class (when it's not necessary sometimes...) or use the keyword out (impossible to use with async). We're going to have a look about the old way before to explain the new way.

Old way with "System.Tuple"

First of all, here's how to create a tuple object:

// Creation with the static method
var nameAndAge = Tuple.Create("jean-luc", 30);

// or with the constructor:
var nameAndAge = new Tuple<string, int>("jean-luc", 30);

Next, Access values of the Tuple can be done with the properties "Item1", "Item2", "Item3", etc. (which is not so convenient...)

var name = nameAndAge.Item1;
var age = nameAndAge.Item2;

New way with "System.ValueTuple"

Careful because this new way implies to add this new reference:  "System.ValueTuple" available with NuGet. When its done, you're ready to declare a literal Tuple like that:

var nameAndAge = (Name: "jean-luc", Age: 30);

and use it direcly with the name of the property:

var name = nameAndAge.Name;

Of course, Tuples are really useful within a method so we can do something like that:

public static (string name, int age) GetPerson()
    return ("jean-luc", 30);

var person = GetPerson();
Console.WriteLine($"Name: {person.name}, Age : {person.age}");

At the Decompilation Level

A way to see exactly how it works is to decompile the code and see the details of what happen:

private static void Main(string[] args)
    ValueTuple<string, int> person = Program.GetPerson();
    Console.WriteLine(string.Format("Nom : {0}, Prenom : {1}", (object) person.Item1, (object) (int) person.Item2));

[return: TupleElementNames(new string[] {"name", "age"})]
public static ValueTuple<string, int> GetPerson()
    return new ValueTuple<string, int>("jean-luc", 30);

As you can see, it makes some replacements and uses the structure ValueTuple ! So the advantage is to use a value type (better handle of the memory) and not anymore a reference type (GC intervention) like the old way.