Source code location: ./collections/collectiontestwithcloning.aspx.cs

using System.Web.UI;
using System.Collections.Generic;
using System;
using System.Web;
using System.Collections.ObjectModel;
using System.Web.Caching;

public partial class CollectionTestWithCloning : Page 
{
    // -----------------------------------------------------------------
    class Book
    {
        string title = null;
        double price = 0.0;

        private Book () { }
        public Book (string title, double price)
        { 
            this.title = title;
            this.price = price;
        }

        public string Title     { get { return this.title; } }
        public double Price     { get { return this.price; } }

        public Book DeepClone ()
        {
            Book clone = new Book ();

            clone.title = this.title;
            clone.price = this.price; 

            return clone;
        }
    }

    // -----------------------------------------------------------------
    class BookCollection : Collection<Book> 
    {
        public BookCollection DeepClone ()
        {
            BookCollection cloneCollection = new BookCollection();

            /* Note: if collection items are objects, instead of primitives,
             * you need to deep clone each one as well before adding to the
             * new collection. */
            foreach (Book book in this)
                cloneCollection.Add (book.DeepClone ());

            return cloneCollection;
        }
    }

    // -----------------------------------------------------------------
    protected override void  OnLoad (EventArgs e)
    {
	    base.OnLoad(e);

        BookCollection books = null;
        int itemCount = 0;


        books = GetBooksInternal ();
        /* The count is 3 */
        itemCount = books.Count;
        books.RemoveAt (1);


        books = GetBooksInternal ();
        /* The count is now 3 because you've modified a snapshot, not
         * a live collection. */
        itemCount = books.Count;
    }

    // -----------------------------------------------------------------
    private BookCollection GetBooksInternal ()
    { 
        Cache           cache = HttpContext.Current.Cache;
        BookCollection  books = cache ["Titles"] as BookCollection;

        if (books == null)
        {
            books = new BookCollection ();

            books.Add (new Book ("Refactoring Databases", 34.95));
            books.Add (new Book ("Refactoring to Patterns", 38.25));
            books.Add (new Book ("Refactoring: Improving the Design of Existing Code", 41.95));

            cache.Insert ("Titles", books);
        }

        return books.DeepClone ();
    }
}