tags:

views:

119

answers:

1

Why anonymous types do not have property setters?

var a = new { Text = "Hello" };
a.Text = "World"; //error
+14  A: 

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
That was fast :-) Thnx
Marko
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
I didn't know that; thanks.
SLaks