4 May 2013

Return multiple Values in C#

Return multiple Values in C#


We can use formal parameters modified by the out keyword. Alternatively, we can allocate a KeyValuePair instance to store the result values.

Tips:
Instead of KeyValuePair you could use a custom class or the Tuple type from the .NET Framework 4.0.

Tuple


Coding

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 GetTwoNumbers()
    {
return new KeyValuePair((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

Return multiple Values in C# using Tuple
public Tuple GetMultipleValue()
{

     return new Tuple(1,2);

}



Other methods for returning multiple Values in C#
Rather than this you can also use object or Collections to return multiple values




No comments:

Post a Comment

Comments Welcome

Implementing OAuth validation in a Web API

 I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...