18

Why do anonymous types not have property setters?

var a = new { Text = "Hello" };
a.Text = "World"; //error
CSJ
  • 3,641
  • 2
  • 19
  • 29
Marko
  • 5,437
  • 4
  • 28
  • 47

1 Answers1

40

Anonymous types are immutable by design.

Anonymous types are meant to hold values, and a type that represents a value should not be mutable.

Also, it would make them unreliable in a dictionary, as the hashcode could change after creation.
Many LINQ methods use Dictionaries, and, especially with delayed evaluation, LINQ with mutable types can lead to subtle mysterious bugs.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 10
    Note that anonymous types in VB are allowed to be partially mutated. In VB you get to state which parts of the anonymous type are mutable; the generated code will not use mutable bits as part of a hash code / equality, so you don't get the "lost in the dictionary" problem. We decided to not implement these extensions in C#. – Eric Lippert Feb 24 '10 at 19:48
  • If you use C# 10+, you can use with keyword for this purpose. For more information, you can read this answer: https://stackoverflow.com/a/76170430/8810311 – Ramil Aliyev 007 May 04 '23 at 07:17