views:

45

answers:

1

Can I define an array or a list from anonymous class?

like this:

persons = new ... [] 
{
 new { ID = 1, Name = "Name1"},
 new { ID = 2, Name = "Name2"}
}
+9  A: 

Yes, you'll just need to type the persons variable implicitly and remove the type specifier from the array creation statement.

var persons = new []
{
    new { ID = 1, Name = "Name1" },
    new { ID = 2, Name = "Name2" }
}
Adam Robinson
Thanks, and Can I define a list directly (without pass an array to the list) ?
Homam
@Homam: Not directly (using list initializer syntax), as you'd have to specify the name of the anonymous type. You can, however, just call `ToList()` at the end of your array declaration and `persons` will then be a `List<>`.
Adam Robinson