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?
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?
you can try this
In C# 4, you will be able to use built-in support for tuples to handle this easily.
In the meantime, there are two options.
First, you can use ref or out parameters to assign values to your parameters, which get passed back to the calling routine.
This looks like:
Second, you can wrap up your return values into a structure or class, and pass them back as members of that structure. KeyValuePair works well for 2 - for more than 2 you would need a custom class or struct.
Ways to do it:
1) KeyValuePair (Best Performance - 0.32 ns):
2) Tuple - 5.40 ns:
3) out (1.64 ns) or ref 4) Create your own custom class/struct
ns -> nanoseconds
Reference: multiple-return-values.
Today, programmers need time & unforgotable methods. A simple, working and quick solution:
Using it in somewhere;
Now that C# 7 has been released, you can use the new included Tuples syntax
which could then be used like this:
You can also provide names to your elements (so they are not "Item1", "Item2" etc). You can do it by adding a name to the signature or the return methods:
or
They can also be deconstructed, which is a pretty nice new feature:
Check out this link to see more examples on what can be done :)
In C#7 There is a new
Tuple
syntax:You can return this as a record:
You can also use the new deconstructor syntax:
Be careful with serialisation however, all this is syntactic sugar - in the actual compiled code this will be a
Tupel<string, int>
(as per the accepted answer) withItem1
andItem2
instead offoo
andbar
. 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 theout
inline, which is better suited in some contexts:However, mostly you'll use this in .NET's own libraries, rather than in you own functions.