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()
{
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With