Collection initializers revisited

Recently there has been a change in the syntax for collection initializers in C# 3.0. Charlie Calvert posted about it here. David Hayden reacts with a question on why you would want this, as it only seems more verbose. Well, here are my best guesses.

To reiterate, the delta from this original and new syntax is listed in bold:

List<Posting> listOfPostings =

    new List<Posting> {

        new Posting { ID = 1, Title=“Certificate Revocation Lists”, Body=“…” },

        new Posting { ID = 2, Title=“Prepping for exam 70-551”, Body=“…” },

        new Posting { ID = 3, Title=“The need for Trusted Root Certificate Authorities”, Body=“…” }


It is now necessary to specify the constructor for each object in the collection initializer. Why? Isn’t it obvious.

Guess 1: Well, now it is certainly more specific.

Guess 2: But, it does allow/remind you to specify a different class than the one in the collection if you want to. These can be derived classes. In the case of a collection based on an interface, say List<IDbConnection>, it would mean different implementing classes.

List<IDbConnection> connections =

  new List<IDbConnection> {

      new SqlConnection { ConnectionString = “…”,  ConnectionTimeout = 60 },

      new OleDbConnection { ConnectionString = “…”,  ConnectionTimeout = 30 },

      new OdbcConnection { ConnectionString = “…”,  ConnectionTimeout = 40 },


Pretty easy, right.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

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

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

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s