Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the properties of anonymous types in C# read-only?

Tags:

c#

c#-3.0

In C#, the properties of anonymous types are read-only:

var person = new { Surname = "Smith", OtherNames = "John" }; person.Surname = "Johnson";  // ERROR: .Surname is read-only 

Of course I can declare a real class if I want writable fields or properties, but regardless, what is the reasoning behind this design decision to make the properties read-only?

like image 271
Roman Starkov Avatar asked Jul 06 '09 22:07

Roman Starkov


People also ask

What is an anonymous type in C?

Updated on: May 2, 2020. In C#, an anonymous type is a type (class) without any name that can contain public read-only properties only. It cannot contain other members, such as fields, methods, events, etc. You create an anonymous type using the new operator with an object initializer syntax.

How do you define anonymous type?

Essentially an anonymous type is a reference type and can be defined using the var keyword. You can have one or more properties in an anonymous type but all of them are read-only. In contrast to a C# class, an anonymous type cannot have a field or a method — it can only have properties.

What is the difference between an anonymous type and 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.

Why anonymous types are better than tuples?

Tradeoffs. You might want to always use ValueTuple over Tuple, and anonymous types, but there are tradeoffs you should consider. The ValueTuple types are mutable, whereas Tuple are read-only. Anonymous types can be used in expression trees, while tuples cannot.


1 Answers

Interesting article on that here. From there ...

... [B]y ensuring that the members do not change, we ensure that the hash is constant for the lifetime of the object.This allows anonymous types to be used with collections like hashtables, without actually losing them when the members are modified. There are a lot of benefits of immutabilty in that, it drastically simplifies the code that uses the object since they can only be assigned values when created and then just used (think threading)

like image 197
JP Alioto Avatar answered Sep 27 '22 21:09

JP Alioto