Generic FIFO Buffer in C#
The System.Collections.Generic Namespace in .NET 2.0 includes various commonly used data structures, but a generic FIFO (First in First out) Buffer is missing. FIFO buffers can be handy at times. For example, recently I needed to implement a 'recently viewed items' feature where the last 25 items viewed by a user will be remembered by the application. This is a session level FIFO buffer that keeps up to 25 items. When this limit is reached, it throws away older items as new items are added to it.
Another application of a FIFO buffer would be keeping a live log (in memory) of recent user activity. For example, at www.houselocator.com we have a FIFO buffer keeping a list of recent homes for sale searches performed by the users.
Since the FIFO buffer I wrote is generic, you can download this and use it for anything that suits your application.
Implementation of the FIFO Buffer
Internally, the FIFO Buffer uses a List<T> with the specified size and a rotating index. Once the size of the buffer is reached, it starts rotating the index and replaces older items with new ones.
An interesting feature is that you can randomly remove items from the Buffer.
Using the FIFO Buffer
Possible Improvements
The Enumeration (For Each Loop) support is implemented with yield statement, which is easy but I believe not the most efficient way of doing it. I didn't have the patience to implement the full IEnumerable<T> Interface.
If you find it helpful, please post a comment and let me know.
Download: FifoBuffer.zip (~1KB)
Posted on March 3, 2009 05:08 by
Haider