Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

498
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda