0

Why is Tuple immutable, and ValueTuple mutable?

ValueTuple<string, string> valTup = new ValueTuple<string, string>("a", "b");
valTup.Item1 = "c";  // OK

Tuple<string, string> tup = new Tuple<string, string>("a", "b");
tup.Item1 = "c";  // Doesn't compile
Yahav
  • 25
  • 1
  • I really dislike "why" questions since only really the language's designers can answer why they made the decisions they did. – ProgrammingLlama Apr 21 '21 at 07:44
  • Does this: [What's the difference between System.ValueTuple and System.Tuple?](https://stackoverflow.com/questions/41084411/whats-the-difference-between-system-valuetuple-and-system-tuple/41084678) answer your question? – Maciej Los Apr 21 '21 at 07:45
  • I assume there has to be some obvious reason behind that, not just a mystery design or implementation detail – Yahav Apr 21 '21 at 07:45
  • 1
    @Yahav yes, there's a reason that's explained in the duplicate. It's performance and the way structs behave. Value types are used to improve performance by avoiding heap allocations. `readonly` can make a tuple itself readonly. C# is developed in the open, with all discussions and design decisions in the [CSharpLang repo on Github](https://github.com/dotnet/csharplang). You can check the initial [proposal](https://github.com/dotnet/roslyn/issues/347) that covers mutability and [the discussions and decisinos](https://github.com/dotnet/csharplang/issues/59) – Panagiotis Kanavos Apr 21 '21 at 08:05

0 Answers0