What is Tuple and when to use?

Asked

Viewed 9,723 times

24

I saw the use in a site and I was left with the doubt of what is Tuple, and when should I use in my project?

1 answer

25


The term means vessel. It serves to put various things inside. Formally is a list of ordered finite elements.

The. NET made it available to group some data that need to be stored, and mainly transported together, without having a specific semantics. That is, it is a way to create a data structure with heterogeneous types, just as it happens with a class or struct, but without creating a type.

He shouldn’t be abused, every time he makes sense it’s best to create a type. Whenever this gives greater robustness, meaning and better organize what you are doing, you must create a type. The tuple should be considered for "emergency" cases, things that will not propagate.

One of the greatest uses iswas to return more than one value in a method. Then you encapsulate these values inside the tuple.

Documentation. Note that there are variations to allow multiple values to be encapsulated. Depending on the amount required, you have to use a different type suitable to accommodate all members.

An alternative to tuples are anonymous types.

Example:

Tuple<int, string, decimal>(1, "exemplo", 10.00m);

Note that members do not have names, one of the reasons it should be avoided, lack semantics. Members can be accessed by generic fields named ItemX, where X is the item number in the order.

Two tuples can be considered compatible if they have the same number of elements, of the same types, in the same order.

The C# 7 has this in the language much better, though the old form may still have some utility in rare cases. The new mechanism has value semantics and does not generate allocation in the heap, so it’s more efficient. The old library tuple can still be useful when you need a longer life temp (almost always a mistake).

  • 7

    Complementing the answer, a tuple is a group of values that only make sense together. For example, a pair of coordinates or a vector, or latitude/longitude, where the isolated numbers do not serve much purpose. So programming languages ensure that a tuple cannot have manipulated elements.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.