Array of dictionaries in C#

59,073

Solution 1

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.

Solution 2

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");

Solution 3

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");

Solution 4

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

Solution 5

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

matrix[0] = new Dictionary<int, string>();
Share:
59,073

Related videos on Youtube

hradecek
Author by

hradecek

while CEO.isAbleToShout(): print "Developers!" print "Yes!"

Updated on February 16, 2020

Comments

  • hradecek
    hradecek over 4 years

    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?

    • leppie
      leppie over 12 years
      Hmmm, you should get a NullReferenceException. Show more code.
    • Adam Mihalcin
      Adam Mihalcin over 12 years
      Have you initialized matrix[0] to a new Dictionary<int, string>? Also, TargetInvocationException is part of the System.Reflection namespace. Where are you using reflection?
  • Igor ostrovsky
    Igor ostrovsky over 12 years
    You can also simlpify "new Dictionary<int, string>[]" to just "new []"
  • Aris
    Aris about 3 years
    simple and elegant!