Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method should return multiple values

Tags:

c#

Hii

I have method in C#, I have to return multiple values from that method with out using collections like arrays. Is there any reliable way ?

like image 758
Jibu P C_Adoor Avatar asked May 27 '10 06:05

Jibu P C_Adoor


2 Answers

Yes, the out keyword:

public void ReturnManyInts(out int int1, out int int2, out int int3)
{
    int1 = 10;
    int2 = 20;
    int3 = 30;
}

then call it like this:

int i1, i2, i3;
ReturnManyInts(out i1, out i2, out i3);

Console.WriteLine(i1);
Console.WriteLine(i2);
Console.WriteLine(i3);

which outputs:

10
20
30

EDIT:

I'm seeing that a lot of posts are suggesting to create your own class for this. This is not necessary as .net provides you with a class to do what they are saying already. The Tuple class.

public Tuple<int, string, char> ReturnMany()
{
    return new Tuple<int, string, char>(1, "some string", 'B');
}

then you can retrieve it like so:

var myTuple = ReturnMany();
myTuple.Item1 ...
myTuple.Item2 ...

there are generic overloads so you can have up to 8 unique types in your tuple.

like image 200
Joel Avatar answered Oct 18 '22 17:10

Joel


Well, you could use:

  • a custom class/struct/type, containing all your values
  • out parameters

I.e.:

class MyValues
{
    public string Val1 { get; set; }
    public int Val2 {get; set; }
}

public MyValues ReturnMyValues();

or

public void ReturnMyValues(out string Val1, out int Val2);
like image 38
Kyle Rosendo Avatar answered Oct 18 '22 17:10

Kyle Rosendo