we are having values stored in Cache-Enterprise library Caching Block. The accessors of the cached item, which is a List, modify the values. We didnt want the Cached Items to get affected.

Hence first we returned a new List(IEnumerator of the CachedItem) This made sure accessors adding and removing items had little effect on the original Cached item.

But we found, all the instances of the List we returned to accessors were ALIVE! Object relational Graph showed a relationship between this list and the EnterpriseLibrary.CacheItem.

So we changed the return to be a newly cloned List. For this we used a LINQ say (from item in Data select new DataClass(item) ).ToList() even when you do as above, the ORG shows there is a relationship between this list and the CacheItem.

Cant we do anything to create a CLONE of the List item which is present in the Enterprise library cache, which DOESNT have ANY relationship with CACHE?!

No correct solution


You would have to make a deep clone of the list, i.e., add a clone of each object in the list (and clone any objects that they may contain, I would suggest having a Clone() method to do this for you), to a new list. As was commented above, a reference is a reference no matter how many times you copy it.

This is how we clone items when pulling them out of the cache. The objects have to be marked serializable.

        using (MemoryStream buffer = new MemoryStream())
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(buffer, objectToClone);
            buffer.Position = 0;
            object temp = formatter.Deserialize(buffer);
            return temp;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow