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
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;
- }
- }
- ValueTuple<int, int> expr_22 = new ValueTuple<int, int>(second, second + first);
- num2 = expr_22.Item1;
- num = expr_22.Item2;
- first = num2;
- second = num;
- static void Swap(ref int x, ref int y)
- {
- (x, y) = (y, x);
- }
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.

Saravanakumar SekaranPosted May 5, 2017, 5:39 AM
Very excellent explanation....
Rajesh KadamPosted Mar 29, 2017, 2:14 AM
Good explanation ..