C# Collections we rarely use: Queue, Stack

There are several Collections supported by C# language, some of which we rarely use in our projects & assignments. Let’s focus on two such collections – Queue and Stack.

Queue

Queue represents a Collection that works on FIFO principle. This is, hence, most appropriate in scenario where first-come first-serve basis is required.  Queue has three methods / behaviors:

  • Enqueue – To add an object into the queue
  • Dequeue – Remove and return the object at the beginning of the queue
  • Peek – Returns (but does not remove) the object at the beginning of the queue

Stack

Stack represents a Collection that works on LIFO principle. A Stack class exposes two methods / behaviors:

  • Push – To add an object in the stack
  • Pull – To retrieve and remove an object from the stack.

Comparison with an example

Let’s put 3 objects in both Queue and Stack : Apple, Orange, and Mellon in the same order.

While retrieving from both, the order would be:

Queue: Apple, Orange, Mellon
Stack: Mellon, Orange, Apple

Related Posts: