Well, in addition to what you mentioned, there is a pretty significant difference in that a tuple can only contain up to eight items. (OK, you can technically make arbitrarily large tuples by making the last argument of the tuple a type of another tuple, but I can't help but feel that you need to be a little crazy to actually do this.)
Unlike tuples in a language such as Python, tuples in C # cannot really be used as general-purpose data structures. One of the most common uses of a tuple in C # is to return multiple values ββfrom a function or pass multiple values ββto functions, which for some reason can take only one (for example, when passing e.Argument
to BackgroundWorker
) or any other situation in which you you cannot worry about creating a custom class, and you cannot use an anonymous type.
Since you need to know exactly how many elements (and what types of elements) they will contain at compile time, tuples are really very limited. Lists, on the other hand, are intended for storing uniform general-purpose data, where you do not always know how many items you will have. I would like to see an example of a code snippet where, as you put it, "any type of data can be equally suitable."
Furthermore, since tuples and lists solve completely different problems, there is probably a rather limited interest in comparing memory / performance effects. But for what it's worth, tuples are implemented as classes, not structures, so they are stored on the heap exactly like lists, and they are not copied when you pass them between functions, unlike value types. However, they implement the IStructuralEquatable
and IStructuralComparable
interfaces, and their Equals
method is implemented in such a way that it returns true: new Tuple<int>(1).Equals(new Tuple<int>(1))
(meanwhile, new List<int>() { 1 }.Equals(new List<int>() { 1 })
is false).
source share