C# Anonymous types cannot be assigned to -- it is read only

user366312 picture user366312 · Oct 11, 2009 · Viewed 19.4k times · Source

What is wrong with this code-snippet?

class Program
{
    static void Main(string[] args)
    {
        var obj = new { Name = "A", Price = 3.003 };

        obj.Name = "asdasd";
        obj.Price = 11.00;

        Console.WriteLine("Name = {0}\nPrice = {1}", obj.Name, obj.Price);

        Console.ReadLine();
    }
}

I am getting the following errors:

Error   5   Property or indexer 'AnonymousType#1.Name' cannot be assigned to -- it is read only .....\CS_30_features.AnonymousTypes\Program.cs  65  13  CS_30_features.AnonymousTypes
Error   6   Property or indexer 'AnonymousType#1.Price' cannot be assigned to -- it is read only    .....\CS_30_features.AnonymousTypes\Program.cs  66  13  CS_30_features.AnonymousTypes

How to re-set values into an anonymous type object?

Answer

JaredPar picture JaredPar · Oct 11, 2009

Anonymous types in C# are immutable and hence do not have property setter methods. You'll need to create a new anonmyous type with the values

obj = new { Name = "asdasd", Price = 11.00 };