How is a tuple different from a class?

how is a tuple different from a class? instead of the following code, we can create a class with three fields and make objects out of it. How is this Heart different from this? This is only a shorthand for the code we write, or it has something to do with speed, given that you cannot modify elements in a tuple.

Tuple<int, string, bool> tuple = new Tuple<int, string, bool>(1, "cat", true); 
+6
source share
4 answers

This eliminates the need to define a new class with custom properties.

It defines equality by the value of three elements, which the barebones class cannot do without special coding. This plus the fact that it is immutable makes it a reasonable candidate for a hash key in the Dictionary .

One of the drawbacks is that the properties are vanilla Item1 , Item2 , etc., so they do not provide any context to the values ​​inside them, where properties like ID , Name , Age will be.

+13
source

Tuple is a class. One that contains whatever data you want (in badly named properties like Item1 ).

Instead, you should make classes to make your code more readable / supported. Its main function is a “quick fix” when you want to link pieces of data without creating a class to store them.

+10
source

Tuples are, in my opinion, an invitation to modeling bad data. Instead of creating the right model, you get a generic object that can hold n properties of an element. Naming is also very common. Item1..ItemN

+4
source

You use Tuples as a means to transfer data between method calls without having to define a new class. It is usually used to return multiple pieces of data from a method, and not to use the "out" parameters.

Keep in mind that the out parameter cannot be used with async / await methods, which is why Tuples come in handy.

You probably want to define a class for your data if you are encoding a reusable class library. However, the tuple works fine in the view layer.

+1
source

Source: https://habr.com/ru/post/979890/


All Articles