Say I define a variable like this:
var o = new { RBI = 108, Name = "Roberto Alomar" };
I can do something like:
Console.WriteLine("{0}", o);
But if I try:
foreach (var i in o) {
Console.WriteLine("{0}", o[i]);
}
I get an error:
foreach statement cannot operate on variables of type 'AnonymousType#1' because 'AnonymousType#1' does not contain a public definition for 'GetEnumerator'
So how does it work under the hood? I’d think that a method for turning an object into a string would have to loop through all the properties to accomplish the task. Is there some special method that allows this to happen, or am I misunderstanding how this works?
Your assumption is that the implementation of ToString is shared between all instances of all anonymous types; that, for example, there is some helper that is logically something like you would do in JavaScript:
This assumption is wrong; there is no single one-size-fits-all implementation of ToString for anonymous types. Rather, the compiler knows what all the properties of the anonymous method are and so it generates a brand-new custom implementation of ToString for every distinct anonymous type.
In C#, the
foreachloop does not do what thefor-inloop does in JavaScript. The C# loop enumerates the members of a collection. The JS loop enumerates the properties of an object.If you want to enumerate the properties of an object in C# you can do that, it just takes a bit more work: