hradecek
hradecek

Reputation: 2513

Array of dictionaries in C#

I would like to use something like this:

Dictionary<int, string>[] matrix = new Dictionary<int, string>[2];

But, when I do:

matrix[0].Add(0, "first str");

It throws " 'TargetInvocationException '...Exception has been thrown by the target of an invocation."

What is the problem? Am I using that array of dictionaries correctly?

Upvotes: 24

Views: 72927

Answers (5)

Thorkil Holm-Jacobsen
Thorkil Holm-Jacobsen

Reputation: 7676

Dictionary<int, string>[] matrix = new Dictionary<int, string>[2];

Doing this allocates the array 'matrix', but the the dictionaries supposed to be contained in that array are never instantiated. You have to create a Dictionary object in all cells in the array by using the new keyword.

matrix[0] = new Dictionary<int, string>();
matrix[0].Add(0, "first str");

Upvotes: 7

Anderson Pimentel
Anderson Pimentel

Reputation: 5757

You forgot to initialize the Dictionary. Just put the line below before adding the item:

matrix[0] = new Dictionary<int, string>();

Upvotes: 4

qxn
qxn

Reputation: 17574

Did you set the array objects to instances of Dictionary?

Dictionary<int, string>[] matrix = new Dictionary<int, string>[2];
matrix[0] = new Dictionary<int, string>();
matrix[1] = new Dictionary<int, string>();
matrix[0].Add(0, "first str");

Upvotes: 10

Andrew Hare
Andrew Hare

Reputation: 351456

Try this:

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

You need to instantiate the dictionaries inside the array before you can use them.

Upvotes: 33

Erik Dietrich
Erik Dietrich

Reputation: 6090

You've initialized the array, but not the dictionary. You need to initialize matrix[0] (though that should cause a null reference exception).

Upvotes: 3

Related Questions