Hey Guys, I’m trying to add to a dictionary, and recieveing the “Object reference not set to an instance of an object.” error. Which I think means that what I’m trying to set it to doesn’t exist?
This is the relevant code:
Dictionary<string, Dictionary<int, Dictionary<string, string>>> user = new Dictionary<string, Dictionary<int, Dictionary<string, string>>>();
user.Add("approved", null);
user.Add("pending", null);
user.Add("declined", null);
int zz = 0;
while (results.Read())
{
Dictionary<string, string> field = new Dictionary<string, string>();
for (int i = 0; i < results.FieldCount; i++)
{
switch (fds[i].ToString())
{
case "gender":
string gend = ((Convert.ToBoolean(results[i])) == false) ? "Male" : "Female";
field.Add("gender", gend);
break;
default:
field.Add(fds[i], results[i].ToString());
break;
}
}
string status = results[0].ToString();
user["approved"].Add(zz, field);
zz++;
}
Is there an issue with the way I am setting the three dictionaries at the beginning?
Thanks,
Psy
You have a third level in your nested dictionary structure, and you’re skipping initialization of the second level. At the very least, you need to add:
What would probably be better, is to do initialization further up front:
Personally, I wouldn’t use a Dictionary for
userat all. It implies that there are a variable number of statuses of a request (or whatever), while in fact there is a finite amount of possibilities: pending, approved, declined. In my opinion, you would be better off writing a class that holds 3 collections for that.This also helps in that you wouldn’t have three nested Dictionaries, making the code more readable. It was enough to confuse you, let alone someone maintaining the code after you 🙂