O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

9.14. Storing Snapshots of Lists in an Array

Problem

You have an ArrayList, Queue, or Stack object and you want to take a snapshot of its current state. (Note that this recipe also works for any other data type that implements the ICollection interface. )

Solution

Use the CopyTo method declared in the ICollection interface. The following method, TakeSnapshotOfList, accepts any type that implements the ICollection interface and takes a snapshot of the entire object’s contents. This snapshot is returned as an object array:

public static object[] TakeSnapshotOfList(ICollection theList)
{
    object[] snapshot = new object[theList.Count]; 
    theList.CopyTo(snapshot, 0);
    return (snapshot);
}

Discussion

The following method creates a Queue object, enqueues some data, and then takes a snapshot of it:

public static void TestListSnapshot( )
{
    Queue someQueue = new Queue( );
    someQueue.Enqueue(1);
    someQueue.Enqueue(2);
    someQueue.Enqueue(3);

    object[] queueSnapshot = TakeSnapshotOfList(someQueue);
}

The TakeSnapshotOfList is useful when you want to record the state of an object that implements the ICollection interface. This “snapshot” can be compared to the original list later on to determine what, if anything, has changed in the list. Multiple snapshots can be taken at various points in an applications run to show the state of the list or lists over time.

The TakeSnapshotOfList method could easily be used as a logging/debugging tool for developers. Take, for example, an ArrayList that is being corrupted ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required