An annonymous type can consume memory in two ways.
First Way
public MyAdd MyFunc()
{
return new MyAdd
{
name = "Mike",
Address = "MyTown"
};
}
var x = MyFunc();
Second Way
x = new { name = "Mike", Address = "MyTown" };
The difference in these two statement is that the c.name is readonly in case of former and
is modifyable in later case.
My question is, in both cases finally an annonymous type is consuming some value so why in
case of structure it is not read only. Is there any internal mechanism for this?
No, in your first case you’re not using an anonymous type. The first code is equivalent to:
No extra type is introduced. I know it looks like the syntax for an anonymous-object-creation-expression or anonymous object initializer (those are the terms the spec uses) but it’s really just using the existing type. This is just an object creation expression using an object initializer – there’s nothing anonymous here.
See sections 7.6.10.1 and 7.6.10.2 of the C# 4 spec for more information.