Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous Type, Enumerator and Lambda expression

Tags:

c#

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));
like image 590
Christophe Debove Avatar asked Mar 16 '12 10:03

Christophe Debove


People also ask

What is the difference between an anonymous type and a regular data type?

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.

What are anonymous data types?

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.

Which of the following selects an anonymous type?

In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class.

How anonymous classes instantiated in .NET can they be passed as function params?

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.


2 Answers

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.

like image 164
nemesv Avatar answered Oct 23 '22 18:10

nemesv


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

like image 4
Louis Kottmann Avatar answered Oct 23 '22 18:10

Louis Kottmann