6

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

I wrote something like this,

 var suspense = new { Name = "Android", Market = string.Empty };
 suspense.Market = "Potential";

.NET throws error

Property or indexer 'AnonymousType#1.Market' cannot be assigned to -- it is read only

I know that AnonymousTypes in C# are immutable, but why? Is this due to some limitation with CLR?

Community
  • 1
  • 1
vinodpthmn
  • 1,062
  • 14
  • 28
  • 1
    I'd rather wonder about the opposite. Why is it so hard to create immutable named types? – CodesInChaos Jan 15 '13 at 11:27
  • http://blogs.msdn.com/b/sreekarc/archive/2007/04/03/immutable-the-new-anonymous-type.aspx and http://blogs.msdn.com/b/ericlippert/archive/2012/01/30/anonymous-types-unify-within-an-assembly-part-two.aspx – Tim Schmelter Jan 15 '13 at 11:27

1 Answers1

3

The motivating factor for driving the immutable anonymous types was because the LINQ APIs used hash tables internally and returning projections of anonymous types that could be modified was a dangerous situation.

You can check :

Immutable types: understand their benefits and use them

Anonymous Types and Object Identities By Tim Ng on MSDN

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • 1
    VB.NET is supporting mutable anonymous type by adding Key to respective field(s), then what is the limitation in c#? – vinodpthmn Jan 17 '13 at 18:51
  • @vinodpthmn - not sure on that you can check the article which also taking vb.net as base language read second artile on msdn – Pranay Rana Jan 17 '13 at 18:52