Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return 2 values from one function

Tags:

i have a function that calculate two locations and i want to get them both, is there a way to get two values returned from the same function, with out turning them into an array. i think something with an out argument or something like that... tnx. here my code:

public static int Location(int p_1, int p_2, int p_3, int p_4)
{
  int  XLocation = p_2 - p_1;
  int YLocation = p_4-p_3;
  return XLocation,YLocation;
}

public void Print()
{
}
like image 537
darko Avatar asked Jan 24 '13 07:01

darko


1 Answers

There are multiple ways for that:

1) Use:

public KeyValuePair<int, int> Location(int p_1, int p_2, int p_3, int p_4)
{                 
    return new KeyValuePair<int,int>(p_2 - p_1, p_4-p_3);
}

or

static Tuple<int, int> Location(int p_1, int p_2, int p_3, int p_4)
{
    return new Tuple<int, int>(p_2 - p_1, p_4-p_3);
}

2) Use custom class like Point

public class Point
{
    public int XLocation { get; set; }
    public int YLocation { get; set; }
}

public static Point Location(int p_1, int p_2, int p_3, int p_4) 
{    
     return new Point 
     {
        XLocation  = p_2 - p_1;
        YLocation = p_4 - p_3;
     }      
 }

3) Use out keyword:

   public static int Location(int p_1, int p_2, int p_3, int p_4, out int XLocation, out int YLocation)
   {
        XLocation = p_2 - p_1;    
        YLocation = p_4 - p_3;
   }

Here is comparison of these methods: multiple-return-values.

The fastest way (best performance) is:

public KeyValuePair<int, int> Location(int p_1, int p_2, int p_3, int p_4)
{                 
    return new KeyValuePair<int,int>(p_2 - p_1, p_4-p_3);
}
like image 160
algreat Avatar answered Sep 27 '22 22:09

algreat