Why do anonymous types not have property setters?
var a = new { Text = "Hello" };
a.Text = "World"; //error
Anonymous types are class types that derive directly from object , and that cannot be cast to any type except object . The compiler provides a name for each anonymous type, although your application cannot access it.
Anonymous type is a class type that contain one or more read only properties whereas dynamic can be any type it may be any type integer, string, object or class. Anonymous types are assigned types by the compiler. Anonymous type is directly derived from System.
The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.
In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With