Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

491
Views
Why the tuple-type list element's value cannot be modified?

In C# 8.0, I can modify the value inside a tuple directly by accessing the field name:

(string name, int score) student = ("Tom", 100);
student.name = "Jack";
Console.WriteLine(student);

And I can modify the list element's property as follow:

var list = new List<Student>();  // assume I have a Student class which has a Name property
list.Add(new Student { Name = "Tom" });
list[0].Name = "Jack";
Console.WriteLine(list[0]);

But why can't I modify the tuple-type element's value like this?

var list = new List<(string name, int score)>();
list.Add(("Tom", 100));
list[0].name = "Jack"; // Error!
Console.WriteLine(list[0]);
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Mutable value types are evil, it's hard to see why this prints "Tom" not "Jack":

(string name, int score) student = ("Tom", 100);
(string name, int score) student2 = student;
student.name = "Jack";
Console.WriteLine(student2);

The reason is that you always create a copy. Because it's not obvious you should avoid mutable value types. To avoid that people will fall into that trap the compiler just allows to modify the object directly via properties(like above). But if you try to do it via a method call you get a compiler error "Cannot modify the return value of ... because it is not a variable".

So this is not allowed:

list[0].name = "Jack";

It would create a new copy of the ValueTuple, assigns a value but doesn't use or store it anywhere.

This compiles because you assign it to a new variable and modify it via property:

(string name, int score) x = list[0];
x.name = "Jack"; // Compiles 

So it compiles but gives you again a suprising result:

Console.WriteLine(list[0]);  // Tom

Read more about it here: Do Not Define Mutable Value Types

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!