views:

376

answers:

3

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?

+5  A: 

Anonymous types are created with read-only properties. You can't assign to them after the object construction.

From Anonymous Types (C# Programming Guide) on MSDN:

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type.

Developer Art
+1  A: 

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. The type name is generated by the compiler and is not available at the source code level. The type of the properties is inferred by the compiler. The following example shows an anonymous type being initialized with two properties called Amount and Message.

http://msdn.microsoft.com/en-us/library/bb397696.aspx

Yannick M.
+7  A: 

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 };
JaredPar
One more thing to note, is that if the new anonymous type has the same number and type of properties in the same order it will be of the same internal type as the first
Yannick M.