In this article, we are going to talk about the queue, stack, and hashtable collections in C#, how to use them and how to use the methods they provide.
If you want to see the complete navigation of this tutorial, you can do that here C# Intermediate Tutorial.
To download the source code, you can visit Collections in C# Source Code.
So, let’s start.
We are going to split this article into the following sections:
- Queue Collection
- The Most Common Methods and Properties
- Stack Collection
- Related Methods and Properties
- Hashtable
- Common Methods In The Hashtable Collection
- Common Properties in the Hashtable Collection
Queue Collection
The queue
collection represents a first-in, first-out collection of objects. This means that we can place our objects in a queue collection in a certain order and remove those objects in the same order. So, the first object which goes in is the first object to go out.
To create an object instance of a queue
collection we can use two different statements.
By using System.Collection.Generic
namespace:
Queue<int> intCollection = new Queue<int>();
And by using System.Collection
namespace:
Queue queueCollection = new Queue();
If we declare an object by providing a type (in our example an int), we can store only integer numbers inside. On the other hand, if we use the second example we can store different data types in a collection because it stores objects.
The Most Common Methods and Properties
The Enqueue
method adds an element inside a collection:
Queue queueCollection = new Queue(); queueCollection.Enqueue(54); queueCollection.Enqueue("John"); queueCollection.Enqueue(54.10); foreach (var item in queueCollection) { Console.WriteLine(item); }
When we want to remove an element at the beginning of the collection and return it, we are going to use the Dequeue
method:
Queue queueCollection1 = new Queue(); queueCollection1.Enqueue(54); queueCollection1.Enqueue("John"); queueCollection1.Enqueue(54.10); int number = Convert.ToInt32(queueCollection1.Dequeue()); Console.WriteLine($"Removed element is: {number}"); Console.WriteLine(); foreach (var item in queueCollection1) { Console.WriteLine(item); }
The Peek
method returns the element at the beginning of the collection but does not remove it:
Queue queueCollection2 = new Queue(); queueCollection2.Enqueue(54); queueCollection2.Enqueue("John"); queueCollection2.Enqueue(54.10); int peekNumber = Convert.ToInt32(queueCollection2.Peek()); Console.WriteLine($"Returned element is: {number}"); Console.WriteLine(); foreach (var item in queueCollection2) { Console.WriteLine(item); }
The Clear
method removes all the elements from a collection.
If we want to check how many elements we have inside a collection, we can use the Count
property:
queueCollection2.Clear(); Console.WriteLine(queueCollection2.Count);
Stack Collection
A stack
collection represents a simple last-in, first-out collection. It means that an element that enters first in a collection will exit last.
As with a Queue
collection, we can use the System.Collection
and System.Collection.Generic
namespaces:
Stack stack = new Stack(); Stack<int> stackInt = new Stack<int>();
Related Methods and Properties
The Push
method inserts an object at the top of the collection:
Stack stack1 = new Stack(); stack1.Push(328); stack1.Push("Fifty Five"); stack1.Push(124.87); foreach (var item in stackCollection1) { Console.WriteLine(item); }
Pop
removes the element which was included last in a collection and returns it:
Stack stackCollection2 = new Stack(); stackCollection2.Push(328); stackCollection2.Push("Fifty Five"); stackCollection2.Push(124.87); double number = Convert.ToDouble(stackCollection2.Pop()); Console.WriteLine($"Element removed from a collection is: {number}"); foreach (var item in stackCollection2) { Console.WriteLine(item); }
Peek
returns an object ready to exit the collection, but it doesn’t remove it:
Stack stackCollection3 = new Stack(); stackCollection3.Push(328); stackCollection3.Push("Fifty Five"); stackCollection3.Push(124.87); double number1 = Convert.ToDouble(stackCollection3.Peek()); Console.WriteLine($"Element returned from a collection is: {number}"); foreach (var item in stackCollection3) { Console.WriteLine(item); }
To remove all objects from a collection, we use the Clear
method.
If we want to count the number of elements, we use the Count
property:
stackCollection3.Clear(); Console.WriteLine(stackCollection3.Count);
Hashtable
The Hashtable represents a collection of a key-value pair that is organized based on the hash code of the key. Differently, from the queue and stack collections, we can instantiate a hashtable object by using the only System.Collections
namespace:
Hashtable hashTable = new Hashtable();
A Hashtable’s constructor has fifteen overloaded constructors.
Common Methods In The Hashtable Collection
The Add
method adds an element with the specified key and value into the collection:
Hashtable hashTable = new Hashtable(); hashTable.Add(Element.First, 174); hashTable.Add(Element.Second, "Sixty"); hashTable.Add(Element.Third, 124.24); foreach (var key in hashTable.Keys) { Console.WriteLine($"Key: {key}, value: {hashTable[key]}"); }
The Remove
method removes the element with the specified key from a collection:
Hashtable hashTable1 = new Hashtable(); hashTable1.Add(Element.First, 174); hashTable1.Add(Element.Second, "Sixty"); hashTable1.Add(Element.Third, 124.24); hashTable1.Remove(Element.Second); foreach (var key in hashTable1.Keys) { Console.WriteLine($"Key: {key}, value: {hashTable[key]}"); }
ContainsKey
determines whether a collection contains a specific key:
if (hashTable.ContainsKey(Element.Second)) { Console.WriteLine($"Collection contains key: {Element.Second} and its value is {hashTable[Element.Second]}"); }
The ContainsValue
method determines whether a collection contains a specific value.
Clear
removes all elements from a collection:
hashTable.Clear();
Common Properties in the Hashtable Collection
Count
property counts the number of elements inside a collection:
Console.WriteLine(hashTable.Count);
Keys
property returns all the keys from a collection and the Value
property returns all the values from a collection:
Hashtable hashTable2 = new Hashtable(); hashTable2.Add(Element.First, 174); hashTable2.Add(Element.Second, "Sixty"); hashTable2.Add(Element.Third, 124.24); var keys = hashTable2.Keys; foreach (var key in keys) { Console.WriteLine(key); } Console.WriteLine(); var values = hashTable2.Values; foreach (var value in values) { Console.WriteLine(value); }
Conclusion
In this article, we have learned:
- To use the Queue collection with its methods
- To use the Stack collection with its methods
- How to use Hashtable collection with its methods
In the next article, we are going to talk about List and Dictionary in C#List and Dictionary in C#.
I didn’t get what the Element.First, .Second, etc. are. Do they enums we create?
That’s correct. This is a custom enumeration. You have a link to the source code at the top of the article, so feel free to inspect it and see for yourself.
Yes, I saw it. Thank you and all the best!
It’s 2018. There are zero good reasons to use non-generic collection types.
I think a tutorial should just not include them at all. Even Microsoft recommend to not use any of the types defined before .Net 2.0 in new projects.
So exit ArrayList, Hashtable, Queue, Stack, etc.
I think the article is excellent. Many new developers do work on old codebase where non-generic collections are heavily used. Is better to know both and decide which one to use. Notwithstanding, I so much value your comment.
When discussing about topics, it would make more sense to group related topics in a single article, and to highlight the practical differences. HashTable has much in common with Dictionary, so it would be more advantageous to compare and contrast those two topics in one article, talking about which is more preferable in what use case, with some practical test results showing the differences in speed and memory utilisation etc. Otherwise this post is just as good as an msdn article, no added value for the reader. Just a thought.
I think it added a lot of values to my students.
Good for you.
Thank you.
Practical examples can be helpful. I frequently use queues when i need an event handler to return quickly but the processing the handler is expected to do might take some time. I spawn a task to process the data from the queue, with a semaphore to signal the task when something is enqueued. The processing task pends on the semaphore if the queue is empty, but processes all items in the queue if it’s not. Decoulping events and event processing is one key use of queues.
Re. Hashtable,
https://stackoverflow.com/questions/301371/why-is-dictionary-preferred-over-hashtable#301384
Hello John. As we stated in the last sentence of this article, we are going to talk about dictionary in the next article. All the best.