✅ Tuples or Reference when returning multiple Variables
What Version would you recommend using?
9 Replies
Why exactly do you have a method such as GetXY instead of just exposing the X, Y coordinates directly?
I kind of don't see the point of that method, it literally just takes in the parameter and returns a value of that argument, seems like a pretty useless method to me.
i know that this is a bad example, but let's say you have to perform calculations on both the x and y coordinates. so lets say you now have this:
this is just a pointless example, there are for sure better ones. but should i use tuples or reference when i have a function that returns 2 or more values
This seems like a very bad use-case for
ref
Return a tuple, or a record struct if you need to return a lot of data.Hi,
there are more possibilities namely returning an obj. Using an out variable etc etc.
The consideration is more that do you want the variables to be changed by another method.
Clean code descripes this part (if I remember correctly as dirty code).
Tupples is a way that you do not have to use an object.
I myself prefer object above tupples because you can directly see what kind it is. However many people have different oppinions.
Again records are really good for this
Neither, return a record
i would not use a record for this specific example
there isn’t really one answer, it depends a lot on the specific scenario
if you are just trying to return a couple of values then i would definitely use a tuple. i would also definitely give names to each element of the tuple
public static (double X, double Y) GetXY(…)
if you think you may add things to that tuple in the future, or if you start passing around these tuples as e.g. parameters into methods, switch to your own data type
i would use an out parameter if you are returning two values that are not “paired” (e.g. returning a bool for success and an out for the actual value). i think out is worse than the tuple here because the values are paireddo not use ref for this. use out https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier
out parameter modifier - C# Reference - C#
out parameter modifier - C# Reference
Okay, thanks!