First, let us see what a Tuple is.
A Tuple may be defined as a data structure that consists of an ordered and finite sequence of immutable, heterogeneous elements that are of fixed sizes. Elements in a Tuple are immutable, i.e., they pertain to a specific type.
A few points related to TUPLE
- Used to store a finite sequence of homogeneous or heterogeneous data of fixed sizes.
- Used to return multiple values from a method.
- Each Tuple instance has a fixed number of items.
- Each item on a Tuple has its own special type (like string or int or any object type).
- Tuples cannot be changed once created.
- Tuples are used to pass multiple values to a method.
- Tuples have a limit of 8 items. If you want to create a Tuple with more items, you have to create nested Tuples. The eighth item of the Tuple should necessarily be another Tuple. Let me explain it with an example.
Tuples were introduced in .NET 4.0 but they had some drawbacks
- They’re classes; i.e., reference types. This means, they must be allocated on the heap, and garbage collected when they’re no longer used. For applications where performance is critical, it can be an issue. Also, the fact that they can be null, is often not desirable.
- The elements in the Tuple don’t have names, or rather, they always have the same names (Item1, Item2, etc), which are not meaningful at all. The Tuple <T1, T2> type conveys no information about what the Tuple actually represents, which makes it a poor choice.
In C# 7.0, the above issues have been resolved
- You will be able to declare Tuple's type “inline”, a little like anonymous types, except they’re not limited to the current method.
- static(int EmpID, string EmpName) EmpDetail() {
- return (1, "Harpreet");
- }
- Before C# 7.0, Tuples items were used like the following.
- var id=empData.Item1;
- var name = empData.Item2;
We cannot have specific names for tuple items but in C# 7.0, this has been resolved. We can specify names for Tuple items like EmpID , EmpName
- var id=empData. EmpID;
- var name = empData. EmpName;
This was all about Tuples. Being a developer, we must take care where to use Tuples so as to take full advantage of them.
Please feel free to ask questions.
Happy Learning!!!