3

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"}
}

1 Answer 1

10

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" }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, and Can I define a list directly (without pass an array to the list) ?
@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<>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.