user1306322
user1306322

Reputation: 8721

Dictionary with array of different data types as value

I'm trying to create a Dictionary with array of integer, string and boolean data types as values. I figured, I should use object[] as value, so declaration would look so:

Dictionary<long, object[]> netObjectArray = new Dictionary<long, object[]>();

Whenever I try setting its element's value to something, VS says there was no such key found in the dictionary.

netObjectArray[key][2] = val; // ex: The given key was not present in the dictionary.

How do I work with this correctly?

UPD1: Somehow, right before throwing this exception, the other dictionary is used without problems in a similar way:

Dictionary<long, Vector2> netPositions = new Dictionary<long, Vector2>();
netPositions[key] = new Vector2(x, y); // works ok

After this locals show the value was assigned and dictionary now contains that entry. Why is this not the case with my other dictionary?

Solution: Before writing a value to an array of values, we must first initialize that array. This code works for me:

try { netObjectArray[key] = netObjectArray[key]; } // if the object is undefined,
catch { netObjectArray[key] = new object[123]; } // this part will create an object
netObjectArray[key][0] = new Vector2(x, y) as object; // and now we can assign a value to it :)

Upvotes: 4

Views: 3699

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

This is expected: if the key is not present in the Dictionary<K,V>, an attempt to read at that key fails. You should assign an empty array to the element at the key before accessing it.

Here is the typical pattern of accessing a dictionary when you do not know if the key is present or not:

object[] data;
if (!netObjectArray.TryGetValue(key, out data)) {
    data = new object[MyObjCount];
    netObjectArray.Add(key, data);
}
data[2] = val;

EDIT (in response to the edit of the question)

You see an exception only when you try reading the dictionary at the previously unknown key. Assignments such as yours

netPositions[key] = new Vector2(x, y);

are allowed, even though the key is not in the dictionary at the time of the assignment: this performs an "insert or update" operation on your dictionary.

Upvotes: 6

ispiro
ispiro

Reputation: 27743

Try something like this:

Dictionary<long, object[]> netObjectArray = new Dictionary<long, object[]>();
for (int i = 0; i < 100; i++) netObjectArray[i] = new object[100];//This is what you're missing.
netObjectArray[key][2] = val;

Upvotes: 1

Joshua Drake
Joshua Drake

Reputation: 2746

Dictionary<string, object[]> complex = new Dictionary<string, object[]>();

complex.Add("1", new object[] { 1, 2 });

object[] value = complex["1"];
value[1] = val;

works for me...

Upvotes: 0

Related Questions