C# Brief training: Tuples
Learn more about C# in 3–10 minutes
Summary
- What is Tuple?
- Understanding and implementing Tuple.
- What are the benefits?
- Conclusion
What is Tuple?
The Tuple allows us(developers) to group multiple elements in a data structure without creating a complex object such as a model, DTO, or ViewModels.
So, you know those moments when you just want to return some values from your method, but I don’t want to create a model or DTO because you will only use that once, or you just don’t want to for some specific reason? Tuples are the best solution for this problem! You can use Tuples to return values directly without creating any other object; it sounds fantastic, doesn’t it? Anyways, Let’s see what it looks like in the topic below!
Understanding and implementing Tuple
Now that you know what Tuples are about let’s look at the code.
Above you can see how to declare a method to returnTuple
without using complex objects for that. You can even return Lists
, Collections
, Already exists complex objects
within your Tuple
, but for simplicity’s sake, I just used strings.
Now, let’s see how you can call your method that returns a Tuple
That’s how you can call a method that returns a Tuple
by explicitly specifying each value you’re expecting; pretty easy, isn’t it? That fits great when you want to use something faster and simple!
What are the benefits?
The most significant benefit of using Tuples is that you don’t need to create a complex object to return multiple elements, which makes your code more legible and understandable.
But careful! Tuples are great but it doesn’t mean you have to use them in every scenario. In most cases, it makes sense to use a complex object.
Conclusion
Well, as you could see, the Tuples are great! Hope you have enjoyed this article. Follow me for more posts like this one. Thanks, see you around!