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

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


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

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

Now using Tuples, it’s become easy to have multiple return values from methods without 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

Tuple<int, double, long, FlightInfo> filghtInfo = GetFlightDetails();

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

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


– Article ends here –

If you have any questions, please feel free to share your questions or comments on the comment box below.

Recommended:   System.ValueTuple - Extended C# Tuples
Share this:

Tags:

1 Comment
  1. Reply
    System.ValueTuple - Extended C# Tuples July 1, 2020 at 1:22 PM

    […] store multiple values belongs to different datatype or object. In my previous article, you can get overview on C# Tuple collection type that provides the basics of Tuples in C#. In this article you will learn extended features of Tuples collection type by importing […]

Leave a reply

Troubleshootyourself
Logo