With :
var Foo = new[]{ new {Something = 321}};
Why can I do (compile) :
Console.WriteLine( Foo[0].Something );
but not :
Foo.ForEach(x => Console.WriteLine(x.Something));
From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.
Anonymous types are class types that derive directly from object , and that cannot be cast to any type except object . The compiler provides a name for each anonymous type, although your application cannot access it.
In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class.
We can't use a anonymous typed variable as a parameter for a method. But we can pass anonymous type for a method that accept dynamic type. Example: public class Employee.
Because Array
only have a static ForEach method:
var Foo = new[] { new { Something = 321 } };
Array.ForEach(Foo, x => Console.WriteLine(x.Something));
compiles and works.
try
Foo.ToList().ForEach(x => Console.WriteLine(x.Something));
instead, as the ForEach extension is only available for lists
EDIT: tested and works.
EDIT2: A few workarounds to make an "anonymous list"
This SO post
This blog post
Another blog post
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With