5.10. 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.
Tip
Note that this recipe also works for any other data type that implements the ICollection interface.
Solution
Use the ToArray extension method on the IEnumerable<T> interface. The following method, TakeSnapshotOfList, accepts any type that implements the IEnumerable<T> interface and takes a snapshot of the entire object's contents. This snapshot is returned as an object array:
public static T[] TakeSnapshotOfList<T>(IEnumerable<T> theList)
{
T[] snapshot = theList.ToArray();
return (snapshot);
}Discussion
The following method creates a Queue<int> object, enqueues some data, and then takes a snapshot of it:
public static void TestListSnapshot()
{
Queue<int> someQueue = new Queue<int>();
someQueue.Enqueue(1);
someQueue.Enqueue(2);
someQueue.Enqueue(3);
int[] queueSnapshot = TakeSnapshotOfList<int>(someQueue);
}The TakeSnapshotOfList<T> 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, changed in the list. Multiple snapshots can be taken at various points in an application's run to show the state of the list or lists over time.
The TakeSnapshotOfList<T> method could easily be used as a logging/debugging tool for developers. Take, for example, a List<T> that is being corrupted at some point in the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access