I have a structure that I need to store in a collection. The structure 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 found that if I add an item to the collection and then try to access the dictionary, the structs values property will never be 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 first load an item and then add it to the collection, the value field is saved.
var collection = new ItemCollection(); var item = new Item(); item.Values.Add("myKey", "myValue"); collection.Add(item); Trace.WriteLine(collection[0].Values["myKey"]);
I have already decided that the structure is the wrong option for this type, and when using the class the problem does not arise, but I am curious that the other is between these two methods. Can anyone explain what is happening?
source share