Setting values for anonymous types
-
Suppose we got the following code snippet: var a = new {i=1, j=2}; How to assign a value for the specific field of that variable? I mean, something like this: a.i = 5; thanks for help
Yoyosch wrote:
How to assign a value for the specific field of that variable?
You can't. When you create an anonymous type the following code is generated:
private static void Main(string[] args)
{
var a;
a = new <>f__AnonymousType0<int, int>(1, 2);
return;
}The special class <>f_AnonymousType0 looks like this:
[CompilerGenerated, DebuggerDisplay(@"\{ i = {i}, j = {j} }", Type="<Anonymous Type>")]
internal sealed class <>f__AnonymousType0<<i>j__TPar, <j>j__TPar>
{
// Fields
[DebuggerBrowsable(0)]
private readonly <i>j__TPar <i>i__Field;
[DebuggerBrowsable(0)]
private readonly <j>j__TPar <j>i__Field;// Methods \[DebuggerHidden\] public <>f\_\_AnonymousType0(<i>j\_\_TPar i, <j>j\_\_TPar j); \[DebuggerHidden\] public override bool Equals(object value); \[DebuggerHidden\] public override int GetHashCode(); \[DebuggerHidden\] public override string ToString(); // Properties public <i>j\_\_TPar i { get; } public <j>j\_\_TPar j { get; }
}
As you can see, there are no setters on any of those properties.
Recent blog posts: * Introduction to LINQ to XML (Part 1) - (Part 2) - (part 3) My website | Blog