So I was wondering if a method can return more than one value? I am trying to write a program which returns the lowest and greatest value of an array:
public int GetMinMaxValue(int[] numbers)
{
int lowest;
int greatest;
foreach (int item in numbers)
{
// some code assigning the values
}
return lowest; // and is it possible to return greatest too?
}
Thanks!
Answer is simply No , you can not send more than one parameter using return
statement.
but logically YES by using parameter modifier out
.
The out
keyword causes arguments to be passed by reference. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.
From MSDN :
Although variables passed as out arguments do not have to be initialized before being passed, the called method is required to assign a value before the method returns.
So before leaving the function you should assign the values for both lowest
and greatest
parameters and if you don't intialize them ofcourse compiler warn you.
Try This:
public int GetMinMaxValue(int[] numbers,out int lowest,out int greatest)
{
lowest=0; //not required if there is a definite assignment happens in your code
greatest=0;//not required if there is a definite assignment happens in your code
foreach (int item in numbers)
{
// some code assigning the values
}
}
You can call above method as below:
int lowest; //not assigned to any value
int greatest;//not assigned to any value
GetMinMaxValue(numbers,out lowest,out greatest)
once after calling the above method your lowest
and greatest
variables will have the values assigned by GetMinMaxValue()
method.
Yes, there is a number of ways to do it:
Tuple<T1,T2>
out
or ref
parameters. In the first three cases you return a single object, but you stuff multiple values in it. In the last case you do not return a value at all, relying on an alternative way of passing the data back to the caller.
No.
But , return type doesn't have to be a primitive number. You can return a List/Array of objects, Or you can return a object which has several properties inside of it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.