C# 7 Tuples
C# 7 release is coming soon and there is a great new feature I’d like to talk to you about – returning multiple values from a method using tuples.
Until now, we could either use out parameters (which are not “comfortable” ) or return a tuple in the following way
This way of doing things have a few problems:
- Accessing the values is using Item1, Item2, and .Item3 properties of the tuple object, there are no names to tell which parameter is which (maybe we got the seconds and the minutes mixed up when reading the different items)
- The syntax of creating the tuple is very verbose and lengthy, its not comfortable to use
- The signature of the method is completely unreadable – what exactly is “Time” and how does it being described by three integers – we have to look at the code to do that (and if we need to read the code to understand what it does then we failed with naming)
Using out parameters we can relieve some of this downsides, but the syntax would remain verbose and not clean.
C# 7 to the rescue
Luckily C# 7 has a neat way of doing the same thing while keeping our code clean and readable. Take a look at the C# 7 version of the above
So whats happening here is that we can name each parameter, return all parameters using a clean syntax of joining all return values inside parenthesis with separating commas. The reader of this method would look as
which both takes the guesswork of understanding what each parameter mean and allows intellisense to help with autocomplete.
When NOT to use this feature
With such an exiting feature we can ask ourselves why not use it all the time. These are my thoughts:
- Consider creating a class containing the relevant data if its usage occurs multiple times or if it has specific domain meaning.
- Consider creating a class if there is a behavior that can be encapsulated into a different type
- Sometimes out variables are more comfortable, as with the TryGetValue method, since we can condition on it “if(TryGetValue(..))”. I wouldn’t like the bool value to be returned via a tuple here. C# 7 also helps makes out parameters more comfortable to use so don’t rule out using out parameters all together.
Using tuples in C# 7 is one of the features I am most exited about, it can make a huge difference writing clean readable code. That said, it’s not something you should use everywhere in code, and there are other constructs that are better suited in some cases, so have that in mind while deciding what to use.
Have fun and see you next time,