Adam's blog formerly game development, now just casual madness

C# Collection Initializers via Extension Methods

An interesting C# feature that I just stumbled across by accident: You can provide a custom collection initializer for any IEnumerable<T> using an extension method. It allows you to turn something like this:

List<Vector3> myList = new List<Vector3>
{
    new Vector3(1.0f, 2.0f, 3.0f),
    new Vector3(4.0f, 5.0f, 6.0f)
};

into this:

List<Vector3> myList = new List<Vector3>
{
    { 1.0f, 2.0f, 3.0f },
    { 4.0f, 5.0f, 6.0f }
};

by simply providing the Add method that is required for collection initializers as an extension method:

public static class Vector3Extensions
{
    public static void Add(this IList<Vector3> list, float x, float y, float z)
    {
        list.Add(new Vector3(x, y, z));
    }
}

Definitely not something for everyday use, but I can imagine it could clean up some data-heavy bits of code a lot. It appears that this was introduced in C# 6.0, along with indexer initializers.

10 of 74