C# Queue

c# queue explained, definition, examples.

In my last post you can find explanation of Stack Collection. Concept of both collections is similar.

Queue is a FIFO(first-in, first out) collection of objects. It’s generic type that is part of  System.Collections.Generic. You can read more about generics in my last post. There are three most important methods in this class:Enqueue(Object),Dequeue(),Peek(). First lets explain the FIFO concept.

queue-line_2991665

 

Queue line can be a good, real world example of FIFO concept. Person who will stand in line first will be served first. Using this concept we can enqueue the items into a queue and get it in the same order. Let’s move on to class syntax.

 

Class signature is similar to other generic collections. You can find more about them here. We need to specify the type of the variable that will be stored in the collection.

Queue<int> queue = new Queue<int>();

 

Let’s look at the methods

 Enqueue(Object)

class Program
{
    static void Main()
    {
	Queue<int> queue = new Queue<int>();
	queue.Enqueue(1);
	queue.Enqueue(2);
	queue.Enqueue(3);
	queue.Enqueue(4);
}
}

We crate new queue and by using Enqueue() method  we add new items to the collection.  Simple as that

Dequeue()

Removes the object at the beginning of your Queue. The algorithmic complexity of this is O(1). It doesn’t loop over elements.

queue.Dequeue();

this method doesn’t take any parameters

Peek()

This method works the same way as in stack. It returns the value without removing it. In this case first value in queue.

queue.Peek();

 

This is not the most popular type of collections, but it can be useful for creating things like for example, player turn system in strategy game. In next post I’ll cover another type of collection, bitArray. Stay Awesome!

 

Author: indiedevart

Indie Games Developer

One thought on “C# Queue”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s