Value Tuples: Returning Multiple Values from a Function in C#
It is a common to want to return multiple values from a function when coding in any programming language. That was possible in C# prior to version 7.0 with the help of the out
parameters. In C# 7.0 it can be done much more elegantly with the help of Value Tuples.
Let’s dive right in!
Imagine we want to return two values from our method. We can use the syntax below to return two floats.
The two methods are exactly the same (excepting their names). There is some syntactic sugar in the compiler to turn the second one into the first more explicit version. Great! Now let’s use our method.
Notice how you can:
- Assign individual returned values to other variables.
- Declare and initialize variables in the same line.
- Use the ValueTuple class explicitly.
You can even mix and match declaration and assignment of the returned values like below. Also you can throw away some of the returned values if you don’t need them.
In this blog post I showed how to quickly use ValueTuples in C# to return multiple values from functions. Also I wanted to make it clear that ValueTuple type is different than the (older) Tuple type in C# and you probably want ValueTuple type. If you want to read more on the subject, Microsoft’s documentation is the best source for .Net related topics:
I have included a full working example in the gist below. Download the whole thing and play around with it. It includes the Value Tuple usage discussed above plus other techniques for dealing with the problem:
- Value Tuples
- Tuples (old not-so-convenient alternative)
- Custom user classes / structs
out
parameters
That’s it for this post. Happy coding!