Initialize Dictionary (C#)

Hi,

I’m wondering if there’s a way to declare and initialize a Dictionary in one statement.

I found this syntax on the web:

static Dictionary<string, int> potionRestoreAmounts =
new Dictionary<string, int>() {
		{"Small", 100},
		{"Medium", 200},
		{"Big", 400},
	};

Visual Studio doesn’t give me any errors but Unity does:

Assets/_Scripts/Helper/Values.cs(40,63): error CS1526: A new expression requires () or [] after type

I tried using different kinds of closures but to no avail. What am I doing wrong ?

try string[ ] and int[ ]

Thanks for the help, but it didn’t work :
Unable to convert ‘string’ to ‘string[ ]’

This may work in Unity 3.0 when they bring the C# specification in line with the current version (currently working off of 2.0)

EDIT: yeah, this was a feature added in C# 3.0

Ah ok, I’ll just do it differently for now.
Thanks for the help guys

sorry, was in a rush and didn’t actually read through the problem, just read the error msg and skimmed the rest. That’s what I get for asusming the problem and not reading :wink:

Dictionaries in general should work fine in unity. As a temporary solution, try adding them through the add function:

static Dictionary<string, int> potionRestoreAmounts =
new Dictionary<string, int>(); 
potionRestoreAmounts.Add("Small", 100);
potionRestoreAmounts.Add("Medium", 200);
potionRestoreAmounts.Add("Big", 400);

Then again, Fizix may be right :stuck_out_tongue: I’m not able to test from work, so, apologies as this is untested.

Yeah, that’s what I wanted to do.

Thanks again :slight_smile:

Ahh, I assumed you knew how to populate a dictionary and was just looking for a shortcut. :smile:

I actually was :wink:
I was just wondering if there was a simpler way, but it’s working now.
Thanks

Dictionary<string, string> demo = new Dictionary<string, string>{ { “a” , “1” } , { “b” , “2” } , { “c” , “3” }};

1 Like

Yea I’m in late, but this is working :slight_smile:

[SerializeField] Dictionary<int, int> resolution = new Dictionary<int, int>{{ 256, 256 }};
1 Like

I’m even later, but in current version i think this is what people are looking for:

        Dictionary<int, int> amounts = new()
        {
            { 1, 0 },
            { 2, 0 },
            { 3, 0 },
            { 4, 0 },
            { 5, 0 },
        };
1 Like

I prefer this syntax:

Dictionary<int, int> amounts = new()
{
    [1] = 0,
    [2] = 0,
    [3] = 0,
    [4] = 0,
    [5] = 0
};

As it clearly and visually separates the key and the value.