Returning more than one result from a method – tuple

Have you ever had a case, when you needed to return more than one parameter from a method? There are a couple of ways to cope with that and tuple might just be what you need.

The problem

Let’s look at the code, where we parse transaction data just to show it on the screen. We have a separate method for that GetTransactionData

And here is the result:

Possible solutions

There are a couple of ways we can approach this. The one that I proposed in the beginning, passing additional return values as out parameters seems to be the worst one. Nevertheless, I saw this construction more than once and there are certain cases it might be useful. For example:

Another approach would be creating a new class to return the result, that might look like this:

This solution is correct in every way. We created a class to represent what we return from a method. Properties are named correctly.
What if we could achieve the same without creating a new class?

Meet tuples

A tuple is a value type that can store a set of data elements. It is a very flexible structure, similar to dynamic types, so you can set names for your properties. Let’s finish talking and jump into code:

Have you noticed, that I haven’t changed the code that’s using a method GetTransactionData? 😲 It is the change that affects only the method itself, but it just makes it simpler and more concise.

Notice how tuple can be defined:

You can create a tuple with new keyword or with parenthesis.

You can specify property names, but if you don’t, you can use default names like Item1, Item2, etc.

Summary

A tuple is a simple, dynamic type when we don’t want to create a class for just a single usage. It is flexible and easy to create.

Would it be useful for you? I will give it a try 😀
 

 

 

One thought on “Returning more than one result from a method – tuple

  1. Thank you for the explanation of Tuples. I have heard the term before but never really researched what a Tuple was and/or how to use it. Too many projects to complete and not enough time to research alternative solutions unless absolutely nec

    Prior to reading this article, I always used either reference or out parameters to return multiple values from methods. this option will change my approach going forward.

    Thank you.

Leave a Reply to Alan Railey Cancel reply

Your email address will not be published. Required fields are marked *