-4

Possible Duplicate:
How can I return multiple values from a function in C#?

C# methods is always like this:

public <return type> funName()
{
//do sth
return someValueformatedasReturnType;
}

how to return 2 values from 1 c# methods? This is a interview question, as many as you know. Thanks!

Community
  • 1
  • 1
SleeplessKnight
  • 2,125
  • 4
  • 20
  • 28

4 Answers4

8

From best to worst (IMHO):

Michael Stum
  • 177,530
  • 117
  • 400
  • 535
  • 2
    Why is a `Tuple` better than out parameters? – George Duckett Nov 23 '11 at 14:56
  • 2
    @GeorgeDuckett That's subjective, but out parameters always add a lot of boilerplate to the caller (needs to declare the variables beforehand) and complicate the method signature (some return types are on the left hand side, some others are in the signature). Of course, it depends, e.g. `int.TryParse` makes sense as an out parameter rather than a `Tuple` or even `Nullable`. – Michael Stum Nov 23 '11 at 14:58
  • 3
    @George - I can't speak for Michael, but http://stackoverflow.com/questions/281036/are-out-parameters-a-bad-thing-in-net this question and the first response summarizes my sentiments on out parameters. – Bob Kaufman Nov 23 '11 at 14:59
4

You have a few options:

  1. output parameters
  2. Tuple
  3. Class that has 2 properties
Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
1

you can use the ref or out keyword for your function parameters.

int i;
int j;

dosomething(out i, out j);    

public void dosomething(out int a, out int b)
{
   a = 1;
   b = 2;
}

after calling the function, i = 1, j = 2. same for ref keyword, msdn tells the difference :)

or return a tuple.

@tudor

look at your names, using out as object name :S, out is used to pass value by reference!

Stefan Koenen
  • 2,289
  • 2
  • 20
  • 32
0

Define a new data type (Class) with the two outputs:

public class Output
{
    public object Val1 { get; set; }
    public object Val2 { get; set; }
}

and return a new object of type Output:

public Output FunName()
{
     Output out = new Output;
     out.Val1 = val1;
     out.Val2 = val2;
     return out;
}
Tudor
  • 61,523
  • 12
  • 102
  • 142