I have just watched a video presenting the new features of C# 7. Among others, it introduces the possibility to return a tuple type (e.g.: (int, int)
, which, I believe, is just a syntactic sugar for Tuple<int, int>
). Thus, if we have a method returning multiple values, there are 3 possibilities in C# on how to do it:
(int first, int second) ReturnTuple()
{
return (1, 2);
}
int ReturnOutParam(out int second)
{
second = 2;
return 1;
}
CustomObject ReturnObject()
{
return new CustomObject
{
First = 1,
Second = 2
};
}
I believe, there are no more ways to do it - if yes, please, correct me.
Which of those three methods is the right one? And in which cases can we use the remaining two? With every new C# release, I have the feeling that there are one or two design patterns that just became obsolete in the .NET world. Some features were very useful (like generics, partials, LINQ, lambdas, async/await or null propagator). Others are very situational (dynamic, nameof). And then there are those that just don't make sense to me (property auto-initializers, tuple return values or local functions).
f(int a, int b, int c)
instead off(Tuple<int, int, int> abc)
orf(CustomClass abc)
? If the values are logically grouped (eg, you would consider making a class out of them if they were used more often), then use the tuple. If not, separate them out. – Hardyout
parameter is optional, then modelling the return as a tuple forces you to change the method name signature, since methods cannot differ by only the return type. Using anout
parameter lets you support an extra optional return value without creating a new method name. – Tennyson