Hooked on LINQ

Hooked on LINQ - Developers' Wiki
for .NET Language Integrated Query

Quick Search

Advanced Search »
Back to C# Language Enhancements.

Collection initializers allows you to populate a collection with data at construction time. The collection must implement ICollection and under the covers, the C# 3.0 compiler simply calls ICollection<T>.Add(T) method for each specified element in order.

Collection initializers allow you to construct and add a set of elements to the new list like this:

List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

Or a more complex example that creates a collection and initializes it with two records (that were assisted in creation by using Object Initializer syntax seen earlier) looks like this:

List<Contact> contacts = new List<Contact> {
     new Contact {LastName = “Doherty”, DOB = new DateTime(1989,1,1)},
     new Contact {LastName = “Wilcox”, DOB = new DateTime(1987,3,3)}
};



Edit

References

Google search: Collection Initializers C#

If you would like to comment on this page, click on the Discuss button located on the top-right of each page. Feel free to edit any mistakes or omissions you find. If you have an objection or find in-appropriate content then contact the administrator. This website is not affiliated with Microsoft®, all content and opinions are those of the specific author and some advice, solutions and article may contain unintentional errors - please use care. Powered by ScrewTurn Wiki version 2.0.33. Some of the icons created by FamFamFam.