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 –