Dictionary - Object referenced not set to an instance of an object - c#

I'm trying to hold a lobby system inside of a dictionary.
private Dictionary<string, Dictionary<string, string>> lobbys;
The first string being the Lobby ID, and the dictionary within the dictionary holding the clients usernames in the lobby.
When I try to create a new 'lobby' in the dictionary like so:
lobbys.Add("dSd244SfasdD", null);
( the "dSd244SfasdD" being the unique lobby ID, and null being the null dictionary I've yet to create (since theres no users in it yet))
I get this error: "Object referenced not set to an instance of an object."
I'm unsure as to what I'm doing wrong, and I'm fairly new to C#. Please help. Thanks :)

You must first instantiate the lobbys Dictionary (which holds the Dictionaries):
lobbys = new Dictionary<string, Dictionary<string, string>>();
Then you can add to this lobbys, and when you do so, you should instantiate those inner dictionaries.
lobbys.Add("dsD244SfasD", new Dictionary<string, string>());
Then, when you add to those inner dictionaries:
lobbys["dsD244fasD"].Add("Client1", "Bob Jones");
lobbys["dsD244fasD"].Add("Client2", "Bill James");

You need to instantiate your dictionary.
lobbys = new Dictionary<string, Dictionary<string, string>();
If its a field in your class, you can initialize it at Field or you can initialize it in the class constructor.

You haven't assigned a value to your variable, so it's got the default value of null. (Don't forget that the value of lobbys isn't an object - it's a reference). You could either assign it a value in your constructor, or in the declaration:
private Dictionary<string, Dictionary<string, string>> lobbys
= new Dictionary<string, Dictionary<string, string>>();
(You may well want to make it a readonly variable at the same time - that wouldn't stop you from changing the dictionary's contents, but it would mean that the variable would always refer to the same dictionary.)

You need create an instance of the object first before use it.
private Dictionary<string, Dictionary<string, string>> lobbys = new Dictionary<string, Dictionary<string, string>>();

private Dictionary<string, Dictionary<string, string>> lobbys
= new Dictionary<string, Dictionary<string, string>>();

Related

Constructor for a Dictionary inside a Dictionary

I am declaring a Dictionary inside a Dictionary like:
var something = new Dictionary<string, Dictionary<string, Object>>();
I want to be able to access both the outer dictionary as well as the inner dictionary with an IgnoreCase StringComparer.
var something = new Dictionary<string, Dictionary<string, Object>>(StringComparer.InvariantCultureIgnoreCase);
As I am only calling the constructor of the outer dictionary, how can I set the StringComparer of the inner dictionary? If I can't call it's constructor, I can see that there is a property Comparer but I'm not sure how I can get access to the inner dictionary object instead of just a Key or Value.
Any suggestions?
When you declare:
var something = new Dictionary<string, Dictionary<string, Object>>();
It has not created any inner dictionary yet. You will initialize inner dictionary when you add data to it, e.g.
if(!something.ContainsKey("somekey"))
{
something["somekey"] = new Dictionary<string, Object>(StringComparer.InvariantCultureIgnoreCase);
}

How to return an object Type given 2 parameters in a dictionary C#

I want to build a dictionary composed by 2 keys and 1 value. Is that possible?
Dictionary<(key1, key2), Type> dict = new Dictionary<(key1, key2), Type>();
Then I want to find in my dictionary by this 2 keys and get the Type. I tried that key1 and key2 were inside an object like this
Dictionary<Object, Type> dict = new Dictionary<Object, Type>();
Then I added into my dictionary an new instance object with the attributes like this
//myObject has many attributes that are empty and I just fill this 2 ones to build my dict
Object myObject = new Object();
myObject.Key1 = "A";
myObject.Key2 = "B";
dict.Add(myObject, (Type)objType);
But, the object that I want to find is loaded with data from DB and has probably many attributes filled.
The thing is when I use the TryGetValue returns nothing, so I think it's because is looking by the same reference which is not the same.
Well the question, how can I build my dictionary with 2 keys (STRING, STRING) and 1 return value (TYPE) in a easy way.
Thanks
Not sure what you mean by 2 keys. If you want a key containing two values, use Tuple, e.g.
Dictionary<Tuple<int, int>, string>
Another option is to use dictionary of dictionary, e.g.
Dictionary<int, Dictionary<int, string>>
I would use the following:
Dictionary<Tuple<string, string>, Type>
From the msdn page here:
http://msdn.microsoft.com/en-us/library/dd270346.aspx
I believe that the Equals method has been overridden for Tuple, so you should get key matching on the contents of the Tuple rather than the object reference.
Adding to dict would be:
dict.Add(new Tuple<string,string>(myObject.Key1, myObject.Key2), (Type)objType);

Add an Array to a Dictionary in C#

I have tried reading the other posts on this subject and can't quite figure this out.
I have a list in C# that I want to put in a dictionary with all of the same keys. The list is this
string[] IN ={"Against","Like","Upon","Through","Of","With","Upon","On","Into","From","by","that","In","About","For"
,"Along","Before","Beneath","At","Across","beside","After","Though","Among","Toward","If"};
I want to create and populate a dictionary with the key being "IN" (the name of the array) and then having each string for the array in the dictionary.
This is what I wrote to create the dictionary (which I am not sure is correct):
Dictionary<string, List<string>> wordDictionary = new Dictionary<string, List<string>> ()
But I am not sure how to populate the dictionary.
Any help would be greatly appreciated as this is the first time I have tried to use a dictionary and I am new to C#
An array is string[], not List<string>, so just do this:
Dictionary<string, string[]> wordDictionary = new Dictionary<string, string[]>();
Now you can add your array as usual.
wordDictionary.Add("IN", IN);
Or:
wordDictionary.Add("IN", new string[] {"Against","Like","Upon","Through","Of","With","Upon","On","Into","From","by","that","In","About","For","Along","Before","Beneath","At","Across","beside","After","Though","Among","Toward","If"});
Dictionary.Add("IN", new List<string>(IN));
...if you want to keep the current signature for your dictionary.
If you change it to Dictionary<string, string[]> then you can just:
Dictionary.Add("IN",IN);
You currently have a string array, not a list - so it should be:
Dictionary<string, string[]> wordDictionary = new Dictionary<string,string[]> ()
Then you can just add items like:
wordDictionary.Add("IN" , IN);
Do you really need to convert your array into a string? You could very well use string[] instead of List in your dictionary:
var wordDictionary = new Dictionary<string, string[]>();
wordDictionary.Add("IN", IN);
But if you really want to convert your string array to List:
var wordDictionary = new Dictionary<string, List<string>>();
wordDictionary.Add("IN", IN.ToList());
Another way to add the array (it's not a list) to the dictionary is to use collection initializer:
var wordDictionary = new Dictionary<string, string[]> { "IN", IN };
This is exactly the same as creating the dictionary in a normal way and then calling Add("IN", IN).

How to Pass dictionary as the value of another dictionary?

var for_cat_dict = new Dictionary<string, string>();
var category_Dict = new Dictionary<string,Dictionary<string,string>>();
for_cat_dict.Add(bean.getId(), bean.getId());
Now I want to add elements to the category_dict. So I tried..
category_Dict.Add(bean.getId(),[for_cat_dict]);
But it doesnt work... any solutions??
It's not really clear what you're trying to do, but
Category_Dict.Add(bean.getId(), for_cat_dict);
should at least compile. Whether it'll do what you want is another matter - it's not clear whether these are local variables, fields etc. (It also looks like you're not following .NET naming conventions in various ways...)
Dictionary<string, string> for_cat_dict = new Dictionary<string, string>();
Dictionary<string, Dictionary<string, string>> Category_Dict = new Dictionary<string, Dictionary<string, string>>();
Category_Dict.Add("somekey", for_cat_dict);

Unable to add to a csharp dictionary definition, recieveing "Object Reference Not Set to an instance..."

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:
user["approved"] = new Dictionary<int, Dictionary<string, string>>();
What would probably be better, is to do initialization further up front:
user.Add("approved", new Dictionary<int, Dictionary<string, string>>());
user.Add("pending", new Dictionary<int, Dictionary<string, string>>());
user.Add("declined", new Dictionary<int, Dictionary<string, string>>());
Personally, I wouldn't use a Dictionary for user at 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 :)
You never create a Dictionary<int, Dictionary<string, string>> object, so in the line of code:
user["approved"].Add(zz, field); // user["approved"] is null
user is a dictionary mapping strings to a dictionary (the details of which aren't important for our purposes). The line
user.Add("approved", null);
adds an entry to user mapping "approved" to the null dictionary. You never set the dictionary that "approved" is mapped to a non-null dictionary so that when you hit the line
user["approved"].Add(zz, field);
you are trying to invoke the method Dictionary.Add on a null dictionary. You can fix this by adding the line
user["approved"] = new Dictionary<int, Dictionary<string, string>>();
The same applies to the other two entries in user.
What about:
user["approved"] = field;
The line:
user["approved"].Add(zz, field);
bangs with a NullReferenceException because when you access user["approved"] it returns null because it's not initialized.

Categories