Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Function returning two values [duplicate]

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?

like image 492
mouthpiec Avatar asked Jun 28 '10 06:06

mouthpiec


1 Answers

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)

like image 117
Dean Harding Avatar answered Sep 20 '22 08:09

Dean Harding