I read the C++ version of this question but didn\'t really understand it.
Can someone please explain clearly if it can be done and how?
In C#7 There is a new Tuple
syntax:
static (string foo, int bar) GetTuple()
{
return ("hello", 5);
}
You can return this as a record:
var result = GetTuple();
var foo = result.foo
// foo == "hello"
You can also use the new deconstructor syntax:
(string foo) = GetTuple();
// foo == "hello"
Be careful with serialisation however, all this is syntactic sugar - in the actual compiled code this will be a Tuple
(as per the accepted answer) with Item1
and Item2
instead of foo
and bar
. That means that serialisation (or deserialisation) will use those property names instead.
So, for serialisation declare a record class and return that instead.
Also new in C#7 is an improved syntax for out
parameters. You can now declare the out
inline, which is better suited in some contexts:
if(int.TryParse("123", out int result)) {
// Do something with result
}
However, mostly you'll use this in .NET's own libraries, rather than in you own functions.