Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous type property setters

Why do anonymous types not have property setters?

var a = new { Text = "Hello" };
a.Text = "World"; //error
like image 660
Marko Avatar asked Feb 24 '10 18:02

Marko


People also ask

What are anonymous data types?

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.

What are difference between anonymous and dynamic types?

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.

What is the difference between an anonymous type and a regular data type?

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.

Which of the following selects an anonymous type?

In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class.


1 Answers

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.

like image 90
SLaks Avatar answered Oct 17 '22 07:10

SLaks