Home>

Because i am a beginner, please do various adbuses.
An array is created using a collection-type Dictionary.

The following error message occurred while implementing the Dictionary array.

Error message
1, System.NullReferenceException: Object reference not set to an instance of an object
2, NullReferenceException: Object reference not set to an instance of an object
Applicable source code
string [] KeyTable = new string [4] {"UP", "DOWN", "RIGHT", "LEFT"};
        int [,] ValueTable = new int [4, 4] {
        {0,0,0,0},
        {0,1,2,0},
        {0,3,2,0},
        {0,0,0,0},
        };
        Dictionary<string, int>[] move = new Dictionary<string, int>[4];
        // number of values
        for (int i = 0;i<4;i ++)
        {
            // number of keys
            for (int j = 0;j<4;j ++)
            {
                // put key and value in Dictionary
                move [i] .Add (KeyTable [i], ValueTable [i, j]);
            }
        }
Tried

Delete move elements

Supplemental information (FW/tool version etc.)

The location of the error is the location of the squid in the for statement.

// Dictionary key and value
move [i] .Add (KeyTable [i], ValueTable [i, j]);

  • Answer # 1

    Dictionaryitself is not instantiated.
    Please generate before entering the value as follows.

    for (int i = 0;i<4;i ++)
            {
                move [i] = new Dictionary<string, int>();// This is required
                // number of keys
                for (int j = 0;j<4;j ++)
                {
                    // put key and value in Dictionary
                    move [i] .Add (KeyTable [i], ValueTable [i, j]);
                }
            }

  • Answer # 2

    The reference type array created by thenewoperator without the initialization list is initialized withnullThe

    So

    Dictionary<string, int>[] move = new Dictionary<string, int>[4];
            // number of values
            for (int i = 0;i<4;i ++)
            {
                // initialize with empty dictionary
                move [i] = new Dictionary<string, int>();
                // number of keys
                for (int j = 0;j<4;j ++)
                {
                    // put key and value in Dictionary
                    move [i] .Add (KeyTable [i], ValueTable [i, j]);
                }
            }


    And should be

  • Answer # 3

    Sorry for the late reply.
    It was done when we changed to KeyTable [j] instead of KeyTable [i].
    Thank you very much.

    The finished source
    for (int i = 0;i<4;i ++)
    {
    move [i] = new Dictionary<string, int>();// This is required

    // number of keys
    for (int j = 0;j<4;j ++)
    {
    // put key and value in Dictionary
    move [i] .Add (KeyTable [j], ValueTable [i, j]);

    }
    }