About tuples in C# 7
Multiple return values for a function is one of the latest features, which comes with C# 7. This is achieved through a syntactic sugar applied on the existing tuples but more details can be found out by already written articles on this theme.
Before trying to use this new feature, please make sure that you install the ValueTuple NuGet package.
Creating Fibonacci series generator
As we already know, Fibonacci series is generated by the formula, which is given below.
- F(1) = 0
- F(2) = 1
- F(n) = F(n-2) + F(n-1)
Let’s write a Fibonacci generator in C#, which is shown below.
- static IEnumerable<int> Fibonacci()
- {
- int first = 0;
- int second = 1;
-
- yield return first;
- yield return second;
-
- while (true)
- {
- int aux = first;
- first = second;
- second = second + aux;
- yield return second;
- }
- }
If we analyze the code, we can see that at line 11; we have to keep it before the last value in order to sum it up with the last value. Well, we don't want that extra variable and fortunatelly we can get rid of it by using the new value tuples.
If we try to rewrite it by taking an advantage of the new tuples, intuitively, we end up with the code given below.
- static IEnumerable<int> Fibonacci()
- {
- int first = 0;
- int second = 1;
-
- yield return first;
- yield return second;
-
- while (true)
- {
- (first, second) = (second, second + first);
- yield return second;
- }
- }
Oh, wait. Does this work? Well ... Yes. Let's take a look to the generated IL code to see what happens under the hood.
- ValueTuple<int, int> expr_22 = new ValueTuple<int, int>(second, second + first);
- num2 = expr_22.Item1;
- num = expr_22.Item2;
- first = num2;
- second = num;
As we can see, our values are reassigned from a temporary ValueTuple. In this way, we are assured that our values are not modified until all the operations are made. This cool trick allows us to write a Swap function in one line of code, by using the same principle, which is given below.
- static void Swap(ref int x, ref int y)
- {
- (x, y) = (y, x);
- }
Conclusion
The new syntactic sugar for ValueTypes is a very useful feature, which will help us to keep our code clean, even if there isn't any performance gain. Anyway, we should take care when we use this feature because this pushes us to break some programming principles. You may want, at some time, to break out the single responsibility and just make a function, which returns a bunch of values. This will make the code less maintainable, but let's not be so pessimistic.