C# 7.0 – Tuples

In this article, we will discuss on Tuple Class in C# and the potential new proposals that is being considered for C#7.

What is Tuple in C#?

A tuple is a data structure that has a specific number and sequence of elements.

A tuple allows you to combine multiple values of possibly different types into a single object without having to create a custom class. This can be useful if you want to write a method that for example returns three related values but you don’t want to create a new class. More On CSharp

System.Tuples namespace supports Tuple class in C#.

The purpose of a tuple is to create a way to return multiple values from a function.

Example:

 

Output:

Create Tuple using Tuple.Create method :

 

Output:

Tuple that returns multiple values in C#:

 

Output:

 

When to use Tuples in C#?

Tuples are commonly used in four ways:

  • To represent a single set of data. For example, a tuple can represent a database record, and its components can represent individual fields of the record.
  • To provide easy access to, and manipulation of, a data set.
  • To return multiple values from a method without using out parameters
  • To pass multiple values to a method through a single parameter. For example, the Thread.Start(Object) method has a single parameter that lets you supply one value to the method that the thread executes at startup time. If you supply a Tuple<t1, t2,=”” t3=””> object as the method argument, you can supply the thread’s startup routine with three items of data.</t1,>

Issues on Tuple Class:

Member Names:

The main problem with Tuple class is it’s Member Names. It does not have any Semantic meaning.

If you see a return type of Tuple<int, int=””> that doesn’t really tell you anything.</int,>

So it is difficult to understand and maintain the code. It would be far more useful if the return type were something like Tuple

So in C#7, Tuples would probably have names, as it makes identifying each member of the Tuple easier.

Let’s look at below example to understand the C#7 proposal on Tuples.

There are 2 proposals being considered for how tuples would be returned from function:

Tuples and Async :

You can use Tuples with Async.

References:
https://github.com/dotnet/roslyn/issues/2136

In the next article, we will discuss on C#7, potential feature: Pattern matching.

Thanks for visiting !!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s