Tuples in C# – Return more than one value from Method

Tuples are useful collection types they allow method to return more than one value. This is the improvement provided in c# version #7. Prior to this, a method is allows to return one value of any type. Tuples are actually an ordered sets of values, and their members can be accessed by position-based names, even in the absence of intentional field names.

Earlier, If there a requirement where your method has two results to be return, then you would need to create separate entity class with member variables. In the method you would need to create the instance of the class and assign result to the member variables of that class inside the method. Finally the method return the class instance.

Recommended:   C# Threading - Thread Class Constructors

Now using Tuples, its become easy to have multiple return values from method with out having any workaround class instances. In the below example you can see Tuple<int,string> instance contains two distinct values returned from the Calculate method.

There is no restriction to have parameter length in Tuples. You can have any number of tuple parameters. In the below example, you can see three string values returned from the tuple instance.

Also, you can create Tuple instance with any type of datatype and class instance. For example

In the above example Tuple instance has type int, double, long, FlightInfo instance. Whare FlightInfo is an entity class.

Recommended:   Visual Studio C# Code Snippets Overview

NuGet package provides System.ValueTuples library that contains extended features using Tuples collections. Further checkout System.ValueTuples extended tuple features article.

Share this:


We will be happy to hear your thoughts

Leave a reply