Accessing a struct collection property from within another collection

Posted by paddyb on Stack Overflow See other posts from Stack Overflow or by paddyb
Published on 2012-09-19T09:17:49Z Indexed on 2012/09/19 9:37 UTC
Read the original article Hit count: 184

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about collections