#836 – Initializing a Generic List with an Object Initializer

Instead of using the Add method repeatedly to populate a generic list, you can use an object initializer to initialize the contents of the list when you declare it.

The object initializer used to initialize a generic list consists of a set of braces, with a comma-separated list of elements within the braces.  If the list’s type is a reference type, each element in the list is instantiated using the new operator.

This use of an object initializer, in initializing a collection, is known as a collection initializer.

            // List of integers
            List<int> favNumbers = new List<int> { 5, 8, 42 };

            // List of Dog objects
            List<Dog> myDogs = new List<Dog>
            {
                new Dog("Kirby", 15),
                new Dog("Ruby", 3)
            };

836-001

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

4 Responses to #836 – Initializing a Generic List with an Object Initializer

  1. Pingback: Dew Drop – May 3, 2013 (#1,540) | Alvin Ashcraft's Morning Dew

  2. Pingback: Interesting .NET Links - May 5 , 2013 | TechBlog

  3. Pingback: The Daily Six Pack: May 6, 2013 | Dirk Strauss

  4. Pingback: #1,133 – Initializing a Dictionary with a Collection Initializer | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: