C# 6.0 – Index Initializers

[7/30/2015] This article was written against a pre-release version of C# 6.0. Be sure to check out the list of my five favorite C# 6.0 features for content written against the release!

After two posts of new C# features that I like I thought it would be fun to change the pace a bit and discuss one that my initial impressions leave me questioning its usefulness: index initializers. I think the reason I’m confused about this feature is that all of the examples I’ve seen around it show dictionary initialization like this:

var numbers =
    new Dictionary<int, string>
    {
        [7] = "seven",
        [9] = "nine",
        [13] = "thirteen"
    };

My problem with this is that C# has allowed initializing dictionaries using a very similar manner since version 3! Here’s the same dictionary initialized with the more traditional object initializer syntax:

var numbers =
    new Dictionary<int, string>
    {
        { 7, "seven" },
        { 9, "nine" },
        { 13, "thirteen" }
    };

So we’ve swapped pairs of curly braces for pairs of square brackets and some commas with assignments? I just don’t see the benefit. It’s not that I’m opposed to index initializers; I’m confused as to why another syntax is needed for something we’ve been able to do in almost exactly the same way for years. The hint that may clear up the reasoning comes from the CTP notes which state:

We are adding a new syntax to object initializers allowing you to set values to keys through any indexer that the new object has

Given that statement, I can see indexer initializers being more useful in conjunction with custom types. Even still, it seems like the only benefit would really be foregoing specific Add method overloads on the custom type but index initializers would still be at the mercy of said type having a compatible indexer property. Unfortunately index initializers aren’t available in the CTP so I can’t really experiment with them at this time and anything else I could say about the feature would be pure speculation.

Advertisements