C# 7.0 [ Tuples in Visual Studio 2017 ]

Tuples in C# 7.0

We often need to return more than one value from a function. In that situation we mostly do one of the following things.

  1. We use Out variables.
  2. We use a custom made type which is specifically created for this purpose by creating a class and using the instances of that class as return types.
  3. System.Tuple <…> return types.
  4. Anonymous types

Each of these methods can be used but they are not built to serve this purpose, are not natural fit and have either limitations or performance issues. Such as

  • Out variables doesn’t support in Async methods.
  • Out variables are heavier on memory so they decreases the performance.
  • System.Tuple<…> allocates an object of type tuple in memory and also in it is lengthy to declare a Tuple object.
  • Custom built types are too much of coding overhead.
  • Anonymous return types are returned through dynamic return types so it has performance overhead as well.

In C# 7.0 tuple types and tuple literals are added. Right now in the Visual Studio 2017 RC version you will have to install a NuGet package System.ValueTuple to avail this feature.

ex6

Please note in the code sample above that the values are automatically assigned the sequential names of Item1,Item2 and so on. We can give them a specific name as well.

ex7

Deconstruction of the Tuple

You can assign the value of a tuple in existing variables or deconstruct the tuple and set the value in separate variables as well instead of having a single variable of the tuple and then accessing the values as properties of that variable. Instead you can set each value in separate variable. If the variables exist you can set them directly otherwise you can declare the variables right there either with the type directly or with the var keyword. Following examples shows the two approaches for deconstructing the Tuple.

thirdtupleexample

fourthtupleexample

Finally below is the code to show you the syntax for how to use it to return the value from a method.

fifthtupleexample

  • Show Comments (0)

Your email address will not be published. Required fields are marked *

comment *

  • name *

  • email *

  • website *