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

C#C# 3.0

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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)

Solution 2 - C#

Unfortunately features like "top level statements" seem to be more important than the ability to pass complex data around and manipulate it as needed without having to create a class for that data. Its a HUGE gap in C# who's omission makes little sense to me. You basically have to use Dictionary as this is the only way to do this. But let me ask any C# designers who might encounter this page, which is cleaner and less verbose between these 2 code snippets?

        var data = new 
        {
            Username = "My Username",
            FullName = "John Smith",
            Age = 22,
            Salary = 11.5,               
            IsEmployee = true,
            DOB = DateTimeOffset.UtcNow,              
        };
        data.FullName = "Hello worlder";

        var data2 = new Dictionary<string, object>
        {
            ["Username"] = "My Username",
            ["FullName"] = "John Smith",
            ["Age"] = 22,
            ["Salary"] = 11.5,
            ["IsEmployee"] = true,
            ["DOB"] = DateTimeOffset.UtcNow,
        };
        data["FullName"] = "john smith";

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoman StarkovView Question on Stackoverflow
Solution 1 - C#JP AliotoView Answer on Stackoverflow
Solution 2 - C#Jerod Edward MoemekaView Answer on Stackoverflow