Introduction of ‘Tuple’ in .NET Framework 4.0, really filled in a missing piece in C#. Apart from giving us the ability to interoperate with functional languages like F# or Python/Ruby, It does offer the convenience of heterogeneous collection which can take form of any class or structure that you would have created otherwise.
In C#, I feel Tuple syntax is still in its early stages and I am hopeful it will take more friendly syntax in next iterations. I have been explaining the concept of Tuple quite a while now during my presentations. Some of the questions that people ask me during my presentations are:
- Do we really need Tuple?
- What is the practical use of Tuple?
My answer to these questions are as below:
- YES – we need Tuple to talk to F# or Python. Let us assume a scenario where you have some code written in Python and it used tuples there. As a developer, you want to use the code in C#. What data type you will use to map to the Python’s ‘tuple’. The representation was entirely missing from C#/.NET. So – to fill this gap, the tuple was launched.
- Here are couple of scenarios where it can be used:
- Assume you have to return multiple values from a function call that are unrelated or of different types. You could still achieve it by creating a custom class/struct but Tuple will give you instant solution and with much convenience. Especially – if the values are unrelated you wouldn’t want to create a custom type just for the sake of returning few values at once.
- All the places where you felt limited by using the KeyValuePair class.