C# 7.0: Tuple Types and Tuple Literals

Basically, a tuple (Tuple in C#) is an ordered sequence, immutable, fixed-size and of heterogeneous objects, i.e., each object being of a specific type. Tuples were introduced in C# with .NET 4.0

// Implementation
private Tuple<int, string> GetData()
{
	int id = 1;
	string name = "test";
	return Tuple.Create(id, name);
}
//Usage
var tuple = GetData();
var message = $"ID is {tuple.Item1} and Name is {tuple.Item2}";

Tuples provide a quick way to group multiple values into a single result, which is very useful when used as a return of function, without the need to create parameters “ref” and / or “out “. It also facilitated with creation of composite keys to collections of type Dictionaryand eliminates the need to create structs or classes or just to fill combobox or lists.

Along with all advantages it has a major problem, tuples does not have an explicit semantic meaning. In other words, the elements in the tuples don’t have names, they have same names (Item1,Item2,Item3…ItemN). It’s hard to read and understand for teams consuming these functions.

To do better at this, C# 7.0 adds tuple types and tuple literals. Tuples still are not part of .NET framework, to use them we can add them using nuget:

PM> install-package System.ValueTuple

Successfully installed ‘System.ValueTuple 4.3.0’ to EntityFrameworkSample
Executing nuget actions took 3.85 sec
Time Elapsed: 00:00:04.5314317

//Implementation
public (int id, string name, double marks) GetData()
{
	var id = 1;
	string name = "test";
	double marks = 95.7;
	return (id, name, marks);
}
//Usage
var tuple = GetData();
var message = $"ID is {tuple.id}, name is {tuple.name} and marks are {tuple.marks}";

Now with new implementation, it looks much better and readability is also good. There is another nice addition, it fully supports async and await.

public async Task<(int id, string name, double marks)> GetData()

Tuples can also be created as:

var t = new (int sum, int count) { sum = 0, count = 0 };

Final comment, whatever changes C# has made are syntactical changes. If you check the compiled code, the tuples are referred as Item1,Items2 etc not id, name or marks.

I hope this helps someone. Any comments and suggestions are welcome.