NDQuattro
NDQuattro

Reputation: 158

Why an array of dictionaries needs initializing 2nd time

public partial class Form1 : Form
{
    Dictionary<string, int>[] db_players = new Dictionary<string, int>[6];      

    public Form1()
    {
        db_players[0] = new Dictionary<string, int>(); 
        db_players[0].Add("qwerty",7);

        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        MessageBox.Show(db_players[0]["qwerty"].ToString());
    }
}

db_players[0].Add() doesnt wonna work without initializing it right there in the constructor. I don't understand why cause I've done it above. Why is that? Sorry for dumb question.

Upvotes: 0

Views: 64

Answers (4)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73502

This line

Dictionary<string, int>[] db_players = new Dictionary<string, int>[6]; 

Creates an array of Dictionary<string, int> with length 6, but it doesn't set what should be in db_players[0], db_players[1], ...

You can initialize the array with a loop:

for (int i=0; i<db_players.Length; i++)
{
    db_players[i] = new Dictionary<string, int>(); 
}

If at all you need to initialize in one statement you can use array initializer syntax.

Dictionary<string, int>[] db_players = new Dictionary<string, int>[]
{
    new Dictionary<string, int>(),
    new Dictionary<string, int>(),
    new Dictionary<string, int>(),
    new Dictionary<string, int>(),
    new Dictionary<string, int>(),
    new Dictionary<string, int>()
};

Upvotes: 1

unkn0wnxx
unkn0wnxx

Reputation: 11

this line Dictionary<string, int>[] db_players = new Dictionary<string, int>[6]; declares and initialize a list of Dictionary arrays named db_players. It does not give db_players its value. Hence, you need db_players[0] = new Dictionary<string, int>(); to assign a dictionary to each object in the array itself.

Upvotes: 0

Sayse
Sayse

Reputation: 43330

You aren't creating a dictionary here.. your creating an array of dictionaries. In C# whenever you initialize an array you are not initializing its elements.

For more information, you can find this Arrays Tutorial on MSDN

Within this link there is a note that states

If you do not initialize an array at the time of declaration, the array members are automatically initialized to the default initial value for the array type

For reference types, this is null. Hence why your code won't work

Upvotes: 2

Marcel N.
Marcel N.

Reputation: 13986

You're declaring an array of 6 dictionaries. Each array element needs to be instantiated individually.

Either do what you do now, or inline-initialize them:

Dictionary<string, int>[] db_players = new Dictionary<string, int>[6] {
  new Dictionary<string, int>(),
  new Dictionary<string, int>(),
  new Dictionary<string, int>(),
  new Dictionary<string, int>(),
  new Dictionary<string, int>(),
  new Dictionary<string, int>()
};

Upvotes: 1

Related Questions