C# Multiple Return Values

Writing

C# Multiple Return Values

A tuple is a data structure that provides an easy way to represent a single set of data. The System.Tuple class provides static methods to create tuple objects.

Many times we need to return multiple values from a method. One common approach is to create a model class and return an instance of that type.

Starting with C# 7, we can easily return multiple values using Tuples.

Tuples allow us to:

  • Create, access, and manipulate a data set
  • Return a data set from a method without using an out parameter
  • Pass multiple values to a method through a single parameter

If the application targets .NET Framework 4.6.2 or lower, install the NuGet package System.ValueTuple.

Use the following command via the Package Manager Console:

PM> Install-Package System.ValueTuple

Below is a simple example using tuples:

using System;

 class Program
 {
    static void Main()
    {
        Tuple<int, string, bool> tuple=new Tuple<int, string, bool>(2610, "Microsoft", true);
        // Using tuple properties.
        if (tuple.Item1 == 1)
        {
            Console.WriteLine(tuple.Item1);
        }
        if (tuple.Item2 == "dog")
        {
            Console.WriteLine(tuple.Item2);
        }
        if (tuple.Item3)
        {
            Console.WriteLine(tuple.Item3);
        }
    }
 }

There are several ways to declare tuples:

// using Tuple<T1, T2, ...>
 Tuple<int, string, bool> t1=new Tuple<int, string, bool>(2610, "Microsoft", true);

 // using tuple syntax
 (int, string, bool) t1=(2610, "Microsoft", true);

 // using named elements
 (int uniqueId, string fromName, bool isValid) t1=(2610, "Microsoft", true);

If this connects with something you are building or untangling,reply by email — the subject line is already written.