C# 6 features – Extension methods visible in collection initializers

Extension methods in collection initializers


Clear collection initialization is possible only thanks to collection initializers. It’s syntax suger for calling ‘Add’ method.

The standard way to add elements to collection could look like:

var dic = new Dictionary<int, string>();
dic.Add(1, "Number 1");
dic.Add(4, "Number 4" );
dic.Add(10, "Number 10");

If you use collection initializers you will get the same effect, but it will be easier to read:

var dic = new Dictionary<int, string>
    { 1, "Number 1" },
    { 4, "Number 4" },
    { 10, "Number 10" }

Underneath it’s transformed to appropriate ‘Add’ method calls. This is possible only because Dictionary<int, string>  has Add(int key, string value)  method defined.

But what if you’d like to define an extension ‘Add’ method? Will it work? Yes and no. It was not possible to leverage extension methods in collection initializers before C# 6. But now, it’s perfectly fine!

Let’s define following extension method:

namespace CollectionInitializerExample.Extensions
    public static class DicExt
        public static void Add(this Dictionary<int, string> dic, int no)
            dic.Add(no, "Number " + no.ToString());

C# 6 allows to use it in collection initializers:

using CollectionInitializerExample.Extensions

var dic = new Dictionary<int, string> { 1, 4, 10 };



Leave a comment

Your email address will not be published. Required fields are marked *