Why an array of dictionaries needs initializing 2nd time - c#

public partial class Form1 : Form
{
Dictionary<string, int>[] db_players = new Dictionary<string, int>[6];
public Form1()
{
db_players[0] = new Dictionary<string, int>();
db_players[0].Add("qwerty",7);
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show(db_players[0]["qwerty"].ToString());
}
}
db_players[0].Add() doesnt wonna work without initializing it right there in the constructor. I don't understand why cause I've done it above. Why is that? Sorry for dumb question.

You aren't creating a dictionary here.. your creating an array of dictionaries. In C# whenever you initialize an array you are not initializing its elements.
For more information, you can find this Arrays Tutorial on MSDN
Within this link there is a note that states
If you do not initialize an array at the time of declaration, the array members are automatically initialized to the default initial value for the array type
For reference types, this is null. Hence why your code won't work

You're declaring an array of 6 dictionaries. Each array element needs to be instantiated individually.
Either do what you do now, or inline-initialize them:
Dictionary<string, int>[] db_players = new Dictionary<string, int>[6] {
new Dictionary<string, int>(),
new Dictionary<string, int>(),
new Dictionary<string, int>(),
new Dictionary<string, int>(),
new Dictionary<string, int>(),
new Dictionary<string, int>()
};

This line
Dictionary<string, int>[] db_players = new Dictionary<string, int>[6];
Creates an array of Dictionary<string, int> with length 6, but it doesn't set what should be in db_players[0], db_players[1], ...
You can initialize the array with a loop:
for (int i=0; i<db_players.Length; i++)
{
db_players[i] = new Dictionary<string, int>();
}
If at all you need to initialize in one statement you can use array initializer syntax.
Dictionary<string, int>[] db_players = new Dictionary<string, int>[]
{
new Dictionary<string, int>(),
new Dictionary<string, int>(),
new Dictionary<string, int>(),
new Dictionary<string, int>(),
new Dictionary<string, int>(),
new Dictionary<string, int>()
};

this line Dictionary<string, int>[] db_players = new Dictionary<string, int>[6]; declares and initialize a list of Dictionary arrays named db_players. It does not give db_players its value. Hence, you need db_players[0] = new Dictionary<string, int>(); to assign a dictionary to each object in the array itself.

Related

Creating Dictionary<string, Dictionary<T, T[]>[]>

In C#, what is the syntax for instantiating and initializing a dictionary containing as values an array of dictionaries, those dictionaries themselves containing arrays as values?
For example, (I believe),
Dictionary<string, Dictionary<string, string[]>[]>?
Here's an example of what I'm trying to do:
private static readonly Dictionary<string, Dictionary<string, DirectoryInfo[]>[]> OrderTypeToFulfillmentDict = new Dictionary<string, Dictionary<string, DirectoryInfo[]>>()
{
{"Type1", new []
{
ProductsInfo.Type1FulfillmentNoSurfacesLocations,
ProductsInfo.Type2FulfillmentSurfacesLocations
}
}
}
where Type1Fulfillment..., and Type2Fulfillment... are already constructed as
Dictionary<string, DirectoryInfo[]>.
This throws the following compiler error:
"Cannot convert from System.Collections.Generic.Dictionary<string, System.IO.DirectoryInfo[]>[] to System.Collections.Generic.Dictionary<string, System.IO.DirectoryInfo[]>"
Edit: The problem was, as Lanorkin pointed out, that I was missing the final [] in the new Dictionary<string, Dictionary<string, DirectoryInfo[]>>(). Still, it goes without saying that this probably isn't something anyone should be trying to do in the first place.
What you've got looks correct, but what you're doing has a real code smell about it that's going to lead to some serious technical debt.
For starters, rather than having an inner Dictionary<string, string[]> model this in a class with methods appropriate to what you're trying to model. Otherwise anyone accessing this type isn't going to have a clue about what it's really modeling.
Something like this:
var dic = new Dictionary<string, Dictionary<int, int[]>[]>
{
{
"key1",
new[]
{
new Dictionary<int, int[]>
{
{1, new[] {1, 2, 3, 4}}
}
}}
};
Dictionary<string, Dictionary<string, string[]>[]> complexDictionary = new Dictionary<string, Dictionary<string, string[]>[]>();
or using the var keyword:
var complexDictionary = new Dictionary<string, Dictionary<string, string[]>[]>();
The following is perfectly valid
// array of dictionary
Dictionary<int, string[]>[] matrix = new Dictionary<int, string[]>[4];
//Dictionary of string and dictionary array
Dictionary<string, Dictionary<string, string[]>[]> dicOfArrays= new Dictionary<string, Dictionary<string, string[]>[]>();
private static readonly Dictionary<string, Dictionary<string, DirectoryInfo[]>>
OrderTypeToFulfillmentDict = new Dictionary<string, Dictionary<string, DirectoryInfo[]>>()
{
{"Type1", new []
{
ProductsInfo.Type1FulfillmentNoSurfacesLocations,
ProductsInfo.Type2FulfillmentSurfacesLocations
}
}
}
You have the wrong type in your variable definition. Remove the final "[]" as you don't want an array of dictionaries.

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

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

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

Convert Generic Dictionary to different type

Is there a quick way to convert a Generic Dictionary from one type to another
I have this
IDictionary<string, string> _commands;
and need to pass it to a function that takes a slightly different typed Dictionary
public void Handle(IDictionary<string, Object> _commands);
I suppose I would write
Handle(_commands.ToDictionary(p => p.Key, p => (object)p.Value));
Not the most efficient thing in the world to do, but until covariance is in, that's the breaks.
maybe this function can be useful for you
IEnumerable<KeyValuePair<string, object>> Convert(IDictionary<string, string> dic) {
foreach(var item in dic) {
yield return new KeyValuePair<string, object>(item.Key, item.Value);
}
}
And you will call it like so:
Handle(Convert(_commands));
could something like this do?
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "One");
dict.Add(2, "Two");
dict.Add(3, "Three");
dict.Add(4, "Four");
dict.Add(5, "Five");
object dictObj = (object)dict;
IDictionary temp = (IDictionary)dictObj;
Dictionary<int, object> objs = new Dictionary<int, object>();
foreach (DictionaryEntry de in temp)
{
objs.Add((int)de.Key, (object)de.Value);
}
Can't you use
Dim myDictionary AS New Dictionary(Of Object, Object)
This would then be able to accept any types

Categories