Which of these patterns should be preferred over the other and why?
foreach(KeyValuePair<string, Dictionary<string, string>> data in
new Dictionary<string, Dictionary<string, string>> {
{"HtmlAttributes", this.HtmlAttributes},
{"Content", this.Content}
})
{
foreach(KeyValuePair<string, string> entry in data.Value)
{
// do something
}
}
or
Dictionary<string, Dictionary<string, string>> data = new Dictionary<string, Dictionary<string, string>>();
data.Add("HtmlAttributes", this.HtmlAttributes);
data.Add("Content", this.Content);
foreach(KeyValuePair<string, IDictionary<string, string>> entry in data)
{
// Do something
}
data.Clear(); // not sure if this is needed either
data = null; // gc object
Please don’t answer with “use var”, as I don’t like using it.
Re: var (2 years later): I must add something to make this right. In retrospect, reading Eric Lipert’s blog post about when and why to use var makes total sense. IF used appropriately, meaning not all the time, it makes perfect sense and it shortens the amount code one needs to read. On the matter of what initialization to use, well the object initializer is fine, but splitting up initialization from the foreach or other processing makes the code more readable.
I would prefer something in between your two versions: split creation and iteration, but use collection initializer.
or equivalently (really, from the point of view of both the compiler and IDE, the following is exactly the same):
Also, if you’re using
Dictionaryjust as a list of pairs, you could use eitherList<KeyValuePair<K, V>>or (on .Net 4)List<Tuple<T1, T2>>.