Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 740
user366312 Avatar asked Oct 11 '09 14:10

user366312


1 Answers

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 }; 
like image 73
JaredPar Avatar answered Sep 28 '22 01:09

JaredPar