22

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?

Josh Darnell
  • 11,096
  • 9
  • 36
  • 63
hradecek
  • 2,265
  • 2
  • 20
  • 29
  • 3
    Hmmm, you should get a `NullReferenceException`. Show more code. – leppie Feb 15 '12 at 20:57
  • 1
    Have you initialized `matrix[0]` to a new `Dictionary`? Also, `TargetInvocationException` is part of the `System.Reflection` namespace. Where are you using reflection? – Adam Mihalcin Feb 15 '12 at 20:58

5 Answers5

30

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.

Andrew Hare
  • 333,516
  • 69
  • 632
  • 626
10

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");
ken
  • 16,712
  • 3
  • 48
  • 71
6
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");
Thorkil Holm-Jacobsen
  • 6,725
  • 4
  • 26
  • 42
3

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

Erik Dietrich
  • 5,980
  • 6
  • 23
  • 37
3

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

matrix[0] = new Dictionary<int, string>();
Anderson Pimentel
  • 4,596
  • 2
  • 30
  • 49