Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

494
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda