Wednesday 21 April 2010

Quick C# Tip: You can use Collection Initializers without creating a Collection

Thanks to some code I saw on Ayende's blog, I’ve just learnt something about C# 3.0 that I never knew before: you don’t have to be creating a brand new collection in order to use a collection initializer.

Here’s what I mean. Collection initializers let you populate a collection without the noise of repeated “Add(…)” calls. Like this:

var myStrings = new List<string> { "A", "B", "C" };

Or if you are fleshing out a collection that is part of another object, you can do this

var instance = new MyType 
               { 
                    MyStrings = new List<string> { "A", "B", "C" }
               };

What I have only just realised is that if the collection property you are assigning to is read only or already has a value, you can still use a collection initializer - you just miss out the construction of the collection type:

var instance = new MyType { MyStrings = { "A", "B", "C" } };

When I first saw this, I didn’t think it was real C# until I checked it myself in LinqPad. But it’s right there in the C#3.0 Specification.

Thanks Ayende!

2 comments:

Anonymous said...

Even nicer:

var myStrings = new [] { "A", "B", "C" }.ToList();

Though lists are basically obsolete now with Linq... Just stick with the immutable IEnumerable.

justinmchase said...

Even nicer:

var myStrings = new [] { "A", "B", "C" }.ToList();

Though lists are basically obsolete now with Linq... Just stick with the immutable IEnumerable.

Post a Comment