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

  • Create an instance by specifying the Item Type and Size of the Buffer. For example, a FIFO Buffer of Product with a size of 25 Items:
    FifoBuffer<Product> buffer = new FifoBuffer<Product>(25)
    
  • Add items to the Buffer using the Add(T item) Method, just like you would Add Items to a List<T>.Add() Method.
  • To Enumerate, use the foreach loop, and items will be returned in the reverse order, the most recently added item being the first.
  • To Remove an Item, use the Remove(T item) or RemoveAt(index) Methods.
  • Reset the Buffer by calling the Clear() Method.
  • And that's about it!

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

Comments

March 13. 2009 12:25

trackback

Trackback from Haiders' .net

Queue vs FIFO Buffer

Haiders' .net

January 28. 2010 05:45

RS

Thats a lovely peice of code. Could you please help me with the VB.NET version? Thanks.

RS

May 9. 2010 09:16

fuel pump

Thanks for post. It’s really informative stuff.
I really like to read.Hope to learn a lot and have a nice experience here! my best regards guys!

fuel pump

Don't Post SPAM

If you are posting a commment just to get a link, don't waste your time!

I have a sophisticated comment moderation system in place, and your comment will not be posted.

Add comment




biuquote
  • Comment
  • Preview
Loading