darko darko - 3 months ago 17
C# Question

how to return 2 values from one function

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()
{
}

Answer

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);
}