How to return multiple values to caller method in c#?

CsharpServer Side ProgrammingProgramming

A Tuple can be used to return multiple values from a method in C#. It allows us to store a data set which contains multiple values that may or may not be related to each other. A latest Tuple called ValueTuple is C# 7.0 (.NET Framework 4.7).

ValueTuples are both performant and referenceable by names the programmer chooses. ValueTuple provides a lightweight mechanism for returning multiple values from the existing methods. ValueTuples will be available under System.ValueTuple NuGet package.

public (int, string, string) GetPerson() { }

Example 1

using System;
namespace DemoApplication{
   class Program{
      public static void Main(){
         var fruits = GetFruits();
         Console.WriteLine($"Fruit Id: {fruits.Item1}, Name: {fruits.Item2}, Size:
         {fruits.Item3}");
         Console.ReadLine();
      }
      static (int, string, string) GetFruits(){
         return (Id: 1, FruitName: "Apple", Size: "Big");
      }
   }
}

Output

The output of the above code is

Fruit Id: 1, Name: Apple, Size: Big

In the above example, we could see that GetFruits() method returns multiple values (int, string, string). The values of the tuples is accessed using fruits.Item1, fruits.Item2, fruits.Item3.

We can also retrieve the individual members by using deconstructing.

(int FruitId, string FruitName, string FruitSize) = GetFruits();

Example 2

using System;
namespace DemoApplication{
   class Program{
      public static void Main(){
         (int FruitId, string FruitName, string FruitSize) = GetFruits();
         Console.WriteLine($"Fruit Id: {FruitId}, Name: {FruitName}, Size:
         {FruitSize}");
         Console.ReadLine();
      }
      static (int, string, string) GetFruits(){
         return (Id: 1, FruitName: "Apple", Size: "Big");
      }
   }
}

Output

The output of the above code is

Fruit Id: 1, Name: Apple, Size: Big
raja
Published on 19-Aug-2020 11:01:29
Advertisements