Glitcher
Glitcher

Reputation: 1184

What is wrong with this Dictionary initializer

I may have gone completely blind, but I can't see anything wrong with this code:

public static Dictionary<States, string> NameMap = new Dictionary<States, string>
{
    [States.State1] = "State1",
    [States.State2] = "State2",
    [States.State3] = "State3",
    [States.State4] = "State4",
    [States.State5] = "State5",
    [States.State6] = "State6"
};

When attempting to build I get a tone of these errors:

Invalid expression term '['

(This points at the first Bracket on each line)

and

Syntax error, ',' expected

This points at the * columns:

[States*.State1]* = "State1",

Any help would be greatly appreciated. Plopping these values in via .Add works fine.

States is an Enum btw.

Upvotes: 1

Views: 305

Answers (2)

hdev
hdev

Reputation: 6527

Your Syntax is right!

You can test it here: http://www.volatileread.com/utilitylibrary/snippetcompiler?id=69450

This called Index initializers

Object and collection initializers are useful for declaratively initializing fields and properties of objects, or giving a collection an initial set of elements. Initializing dictionaries and other objects with indexers is less elegant. We are adding a new syntax to object initializers allowing you to set values to keys through any indexer that the new object has

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

Source: https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6

Upvotes: 2

Glitcher
Glitcher

Reputation: 1184

Issue was caused by Resharper simply assuming I was using the C# 6 compiler and 'correcting' my code accordingly. Upon examination, I'm not using C# 6, and Resharper is lucky I haven't deleted it

Upvotes: 4

Related Questions