I have a struct that I need to store in a collection. The struct has a property that returns a Dictionary.
public struct Item
{
private IDictionary<string, string> values;
public IDictionary<string, string> Values
{
get
{
return this.values ?? (this.values = new Dictionary<string, string>());
}
}
}
public class ItemCollection : Collection<Item> {}
When testing I’ve found that if I add the item to the collection and then try to access the dictionary the structs values property is never updated.
var collection = new ItemCollection { new Item() }; // pre-loaded with an item
collection[0].Values.Add("myKey", "myValue");
Trace.WriteLine(collection[0].Values["myKey"]); // KeyNotFoundException here
However if I load up the item first and then add it to a collection the values field is maintained.
var collection = new ItemCollection();
var item = new Item();
item.Values.Add("myKey", "myValue");
collection.Add(item);
Trace.WriteLine(collection[0].Values["myKey"]); // ok
I’ve already decided that a struct is the wrong option for this type, and when using a class the issue doesn’t occur, but I’m curious what’s different between the two methods. Can anybody explain what’s happening?
As it was mentioned before, change
struct Itemtoclass Item. When you usestruct, an expressioncollection[0]returns not a reference to object created innew ItemCollection { new Item() }but rather creates a copy of it and gives it to you.