Tutorial :C# Function returning two values [duplicate]



Question:

This question already has an answer here:

I would like to have a function in which I will input an array and as a result i need another array and an integer value. Is this possible?

Example:

private int[] FunctionName (int[] InputArray)  {      //some function made here      int intResult = xxxxx      int[] array = xxxxx        return intResult; //but here i need also to pass the new array!  }  

EDIT:

what i need is the following (updated);

I have a function that as an input takes nothing, but internally generates two items - array + integer. I need to return these two items? Can you also let me know how can I then use this items?

How this can be done?


Solution:1

You have a couple of options (in order of what would be my preference):

Create a class and return that:

class MyResult  {      public int[] Array { get; set; }      public int Integer { get; set; }  }    ...    private MyResult FunctionName(int[] inputArray)  {      return new MyResult { Array = ..., Integer = ... };  }  

You could use a built-in type that basically makes the definition of the custom class a bit easier:

private Tuple<int[], int> FunctionName(int[] inputArray)  {      return Tuple.Create( ..., ... );  }  

You can use an out parameter:

private int[] FunctionName(int[] inputArray, out int integerResult)  {      integerResult = 123;      return new int[] { ... };  }  

(Obviously function names and properties, etc, are just examples... I assume you'll pick more meaningful names)


Solution:2

Try using a Tuple type. It is meant to pair related values without having to define a new type.

public Tuple<int[],int> MyFunction(int[] inputArray) {          ...    int[] resultArray = ...    int resultValue = ...;    return Tuple.Create(resultArray,resultValue);  }  

You can then access the values through the Item1 and Item2 properties.

Tuple<int[],int> tuple = MyFunction(myArray);  int[] array = tuple.Item1;  int value = tuple.Item2;  

References


Solution:3

you can use "out" keyword on the parameter


Solution:4

You have two options - you either wrap the array and the integer value into a class or a structure and return an instance of it. The other option is to use out parameters - link.


Solution:5

There are three easy ways to do this:

First method:

//use a struct to wrap values:  struct returnPair { public int number; public int[] array; }  private returnPair MyFunction(int arg1) {     return new returnPair { number = ...., array = ...., };  }  

Prefer struct to class because it is passed by value and thus avoids some mutability issues, and also avoids dealing with null. Prefer fields to properties because fields are shorter to declare and have no downside in this use-case.

Second method:

Use a tuple via Tuple.Create(....,....) - this is explained in other answers.

Third method:

Use a continuation/callback. Don't overdo it; but sometimes this is a good alternative; particularly when you want to "return" multiple items but can't easily use the yield return strategy, such as when dealing with heavily recursive functions, or enumerating more than once isn't supported. It also has the advantage of permitting quite readable calls - better than tuples in C#.

private void MyFunction(int arg1, Action<int, int[]> yieldF) {     yieldF(....num, ....arr);     yieldF(....num2, ....arr2); //and again...  }  //call like this note that unlike a tuple params are labelled and readable,  //basically like a foreach loop with multiple loop variables:  MyFunction(3+4+5, (intp, arrp) => {      Do-My-Side-Effect  });  

Sneaky Method :-)

If you're sneaky (not recommended) you can even combine the first and third options and abuse type-inference to get named parameters wrapped in an auto-generated readonly class :-)

private T MyFunction<T>(int arg1, Func<int, int[], T> yieldF) {     return yieldF(....num2, ....arr2); //and again...  }  //...  var anontuple = MyFunction(3+4+5, (intp, arrp) => new { IntP = intp, ArrP = arrp, });  int foobar = anontuple.IntP + anontuple.ArrP[0];//with intellisense...  


Solution:6

Possible. Use structs.

struct retArguments{      public int result;      public int array[];  } ;  

Also you can visit http://msdn.microsoft.com/en-us/library/aa288471%28VS.71%29.aspx


Solution:7

There are several options, using out and ref arrays, but I would not recommend them as they promote programming with side effects (meaning you don't always know where a variable may change), making your code harder to understand.

Another option is to create a class to hold the return values you need - this works well if the result you need is composed of different types (such as an int and a int[]). This is a good choice if the returned values belong together and logically belong together and you can reuse the class.

If not, you can always use the built in generic Tuple classes, which are designed to hold multiple items together:

private Tuple<int,int[]> FunctionName (int[] InputArray)  {      int intRes = ...;      int intArrayRes = ...'      Tuple<int,int[]> myResult = Tuple.Create(intRes, intArrayRes);      ....      return myResult;   }  

You can access the values by using the various ItemX properties:

Tuple<int,int[]> result = FunctionName(myArray);  result.Item1; 'Gets the integer  result.Item2; 'Gets the integer array  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »