Skip to main content

Multiple Return Values

 How to return multiple values from function?

As normally method return single value
eg.  private int add(int a, int b)
{
int result=a+b;
return result;
}
but in situation where we need to return more than one value this article is helpful.


Methods return only one value. This value can be a type instance with multiple fields. If you need to return multiple values from a method, you can use out parameters or return a type instance containing all the values. These approaches require different syntax forms. They result in different performance metrics.

Example

We first show an example program that demonstrates ways you can use multiple return values. The two ways of returning multiple values are using output parameters, which are formal parameters modified by the out keyword, and allocating a KeyValuePair instance to store the result values.

Note: Instead of KeyValuePair, you could a custom class or the Tuple type from the .NET Framework 4.0.
Program that uses multiple return values [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void GetTwoNumbers(out int number1, out int number2)
    {
 number1 = (int)Math.Pow(2, 2);
 number2 = (int)Math.Pow(3, 2);
    }

    static KeyValuePair<int, int> GetTwoNumbers()
    {
 return new KeyValuePair<int, int>((int)Math.Pow(2, 2), (int)Math.Pow(3, 2));
    }

    static void Main()
    {
 // Use out parameters for multiple return values.
 int value1;
 int value2;
 GetTwoNumbers(out value1, out value2);
 Console.WriteLine(value1);
 Console.WriteLine(value2);

 // Use struct for multiple return values.
 var pair = GetTwoNumbers();
 Console.WriteLine(pair.Key);
 Console.WriteLine(pair.Value);
    }
}

Output

4
9
4
9
Out keywordThe program contains three methods: two alternate implementations of the GetTwoNumbers method, and the Main entry point, where control flow begins. The first version of the GetTwoNumbers method uses two output parameters, which are described with the out modifier. This version assigns the storage locations passed in by the out parameters in the method body.
Out Parameter Math.Pow MethodKeyValuePair (Key and Value properties)KeyValuePair. The program also describes an alternate GetTwoNumbers method, which is ordered second in the lexical source. This version returns a KeyValuePair generic struct instance instead of using output parameters. The two numbers are specified as the key and value of the struct and then this struct is returned.
KeyValuePair Hints Struct Examples

Performance

Performance optimizationWe next consider the performance aspects of returning multiple values. The first implementation, which uses out parameters, was found to be somewhat slower than the second, which uses the KeyValuePair.
In this benchmark, inlining might account for why out parameters were slower: the compiler might be less likely to inline a method that uses out parameters. The KeyValuePair is allocated on the stack, so it ends up being faster. The Tuple, meanwhile, is allocated on the heap which ends up being much slower.
Program that benchmarks multiple return values [C#]

using System;
using System.Collections.Generic;
using System.Diagnostics;

class Program
{
    static void GetTwoNumbersA(out int number1, out int number2)
    {
 number1 = 1;
 number2 = 2;
    }

    static KeyValuePair<int, int> GetTwoNumbersB()
    {
 return new KeyValuePair<int, int>(1, 2);
    }

    static Tuple<int, int> GetTwoNumbersC()
    {
 return new Tuple<int, int>(1, 2);
    }

    static void Main()
    {
 const int max = 100000000;
 var s1 = Stopwatch.StartNew();
 for (int i = 0; i < max; i++)
 {
     int a;
     int b;
     GetTwoNumbersA(out a, out b);
     if (a + b != 3)
     {
  throw new Exception();
     }
 }
 s1.Stop();
 var s2 = Stopwatch.StartNew();
 for (int i = 0; i < max; i++)
 {
     var pair = GetTwoNumbersB();
     int a = pair.Key;
     int b = pair.Value;
     if (a + b != 3)
     {
  throw new Exception();
     }
 }
 s2.Stop();
 var s3 = Stopwatch.StartNew();
 for (int i = 0; i < max; i++)
 {
     var tuple = GetTwoNumbersC();
     int a = tuple.Item1;
     int b = tuple.Item2;
     if (a + b != 3)
     {
  throw new Exception();
     }
 }
 s3.Stop();
 Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
     max).ToString("0.00 ns"));
 Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
     max).ToString("0.00 ns"));
 Console.WriteLine(((double)(s3.Elapsed.TotalMilliseconds * 1000000) /
     max).ToString("0.00 ns"));
 Console.Read();
    }
}

Result

1.64 ns [out]
0.32 ns [KeyValuePair]
5.40 ns [Tuple]

Comments

Popular posts from this blog

Creating package in Oracle Database using Toad For Oracle

What are Packages in Oracle Database A package is  a group   of procedures, functions,  variables   and  SQL statements   created as a single unit. It is used to store together related objects. A package has two parts, Package  Specification  and Package Body.

Resolving 'Setup Account Privileges' error while installing SQL Server

A new installation of Microsoft SQL Server 2012 or Microsoft SQL Server 2008 R2 fails You see the following error message when you try to install a new instance of SQL Server 2012 or SQL Server 2008 R2: Rule "Setup account privileges" failed.

Creating Oracle stored Procedures using TOAD for Oracle

In a database management system, a  stored procedure  is a set of Structured Query Language (SQL) statements with an assigned name that's stored in the database in compiled form so that it can be shared by a number of programs. The use of  stored procedures  can be helpful in controlling  access to data, preserving  data integrity  and  improving  productivity.