C# Multiple Return Values

Many times we wanted to return multiple values, one solution is to create a model class and returning an instance of it.

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 out parameter
  • Pass multiple values to a method through a single parameter

If applications target .NET Framework is 4.6.2 or lower then install NuGet package System.ValueTuple.

Use below command to install via Package Manager CLI.

 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 various ways of declaring Tuples as below:

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

 // without Tuple keyword
 (int, string, bool) t1=(2610, "Microsoft", true);

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