Stack Class Using C# 101

Introduction and Background

 
In this article, we are going to tackle the basics of Stack class which behaves in a simple last-in-first-out (LIFO) manner. The idea behind this article is combining the two subjects which are non-generic and generic Stack class with code samples. So, readers can see the differences in the usage of the two.
 

What is a Stack Collection? 

 
The Stack is a specialized type of collection that stores elements in a last-in-first-out manner. In other words, within the stack collection, you can only add and/or remove an item is at the top of the stack. It is also good to mention that it is available within the generic and non-generic collection namespace.
 
Let us see the important methods and properties that you need to be familiar with in order to use this specialized class collection.
 
Method
Definition/Usage
Push
Add an item to the stack collection
Peek
Checks the top item of the stack collection
Pop
Removes the current top item of the stack collection
Contains
Checks whether the stack collection contains a certain item
Clear
Removes all the items within the stack collection
 

What is the Difference between non-generic Stack to a generic Stack collection?

 
Of course, for experienced developers the answer is obvious. You need to know the difference between the generic collections and non-generic collections to know the difference. Let’s get back to that later.
 
However; for beginners let me share my experience. While I was doing the sample codes, I could answer with certainty the main difference between the two non-generic and generic Stack class. See my answers in the bullet list below.
  • When using a non-generic Stack class, you can add any object within the collection. Meaning you can add anything, it could be a string, number, custom type.
  • When using a generic Stack class, you can only add the type that you have declared when you have initialized it.
Therefore; it all boils down to the concept of “Generics”. Moreover; to answer the difference between the generic collections and non-generic collections. Just remember non-generic collections store elements internally as objects while generic collections store elements internally as actual types.
 
Wo-hoo! Hopefully, that makes sense. Now, let’s get started by seeing sample codes.
 
Code Samples
 
Before we start, I would like you to see the Book class which is used with the entire sample codes, specifically with the Stack generic collection class. 
  1. using System;  
  2. using System.Diagnostics.CodeAnalysis;  
  3.   
  4. namespace Stacks_Non_Generic_And_Generic_Csharp_101.Model  
  5. {  
  6.     public enum BookCategory  
  7.     {  
  8.         IT = 0,  
  9.         CRIME = 1,  
  10.         SPORTS = 2  
  11.     }  
  12.       
  13.     public class Book : IEquatable<Book>  
  14.     {  
  15.         public int Id { getset; }  
  16.   
  17.         public string Title { getset; }  
  18.   
  19.         public BookCategory BookCategory { getset; }  
  20.   
  21.         public bool Equals([AllowNull] Book other)  
  22.         {  
  23.             return this.Title == other.Title;  
  24.         }  
  25.   
  26.         public override string ToString()  
  27.         {  
  28.             return this.Title;  
  29.         }  
  30.     }  
  31. }   
Different ways to create a new instance of the Stack object.
  1. [Fact]  
  2. public void Test_Different_Ways_To_Create_New_Instance_Stack_NonGeneric()  
  3. {  
  4.     //create a new instance of stack   
  5.     Stack stackofBooks = new Stack();  
  6.   
  7.     //checks whether the declared stackofBooks is not null  
  8.     Assert.NotNull(stackofBooks);  
  9.     //checks whether the stackofBooks collection count is zero  
  10.     //because we haven't added anyting yet  
  11.     Assert.True(stackofBooks.Count == 0);  
  12.   
  13.     //create a new instance of string collection of books and initialize it  
  14.     string[] books = new string[] { "C# in Depth""Pro C# 7""C# 5.0 In A Nutshell" };  
  15.   
  16.     //create a new instance of stack and pass the book collection  
  17.     Stack stackOfBooks_Csharp = new Stack(books);  
  18.   
  19.     //checks whether the declared stackofBooks is not null  
  20.     Assert.NotNull(stackOfBooks_Csharp);  
  21.     //checks whether the stackOfBooks collection count is greater than zero  
  22.     Assert.True(stackOfBooks_Csharp.Count > 0);  
  23. }  
  1. [Fact]  
  2. public void Test_Different_Ways_To_Create_New_Instance_Generic_Stack()  
  3. {  
  4.     //create a new instance of generic stack   
  5.     Stack<Book> stackofBooks = new Stack<Book>();  
  6.   
  7.     //checks whether the declared stackofBooks is not null  
  8.     Assert.NotNull(stackofBooks);  
  9.     //checks whether the stackofBooks collection count is zero  
  10.     //because we haven't added anyting yet  
  11.     Assert.True(stackofBooks.Count == 0);  
  12.   
  13.     //create a new instance of book collection and initialize it  
  14.     var books = new Book[] {  
  15.         new Book { Id =1, Title = "C# in Depth", BookCategory = BookCategory.IT } ,  
  16.         new Book { Id =2, Title = "Pro C# 7"  , BookCategory = BookCategory.IT },  
  17.         new Book { Id =3, Title = "C# 5.0 In A Nutshell", BookCategory = BookCategory.IT  } };  
  18.   
  19.     //create a new instance of generic stack and pass the book collection  
  20.     Stack<Book> stackOfBooks_Csharp = new Stack<Book>(books);  
  21.   
  22.     //checks whether the declared stackofBooks is not null  
  23.     Assert.NotNull(stackOfBooks_Csharp);  
  24.     //checks whether the stackOfBooks collection count is greater than zero  
  25.     Assert.True(stackOfBooks_Csharp.Count > 0);  
  26. }  
Adding items to stack collection.
  1. [Fact]  
  2. public void Test_AddValues_To_Stack_NonGeneric()  
  3. {   
  4.     //create a new instance of stack   
  5.     Stack stackOfBooks_Csharp = new Stack();  
  6.     //checks whether the stackofBooks collection count is zero  
  7.     Assert.True(stackOfBooks_Csharp.Count == 0);  
  8.   
  9.     //lets push some books at the stack  
  10.     stackOfBooks_Csharp.Push("C# in Depth");  
  11.     stackOfBooks_Csharp.Push("Pro C# 7");  
  12.     stackOfBooks_Csharp.Push("C# 5.0 In A Nutshell");  
  13.   
  14.     //lets count if there are 3 elements/items inside the stack  
  15.     Assert.True(stackOfBooks_Csharp.Count == 3);  
  16. }  
  1. [Fact]  
  2. public void Test_AddValues_To_Generic_Stack()  
  3. {  
  4.     //create a new instance of stack   
  5.     Stack<Book> stackOfBooks_Csharp = new Stack<Book>();  
  6.     //checks whether the stackofBooks collection count is zero  
  7.     Assert.True(stackOfBooks_Csharp.Count == 0);  
  8.   
  9.     //lets push some books at the stack  
  10.     stackOfBooks_Csharp.Push(new Book { Id = 1, Title = "C# in Depth", BookCategory = BookCategory.IT });  
  11.     stackOfBooks_Csharp.Push(new Book { Id = 2, Title = "Pro C# 7", BookCategory = BookCategory.IT });  
  12.     stackOfBooks_Csharp.Push(new Book { Id = 3, Title = "C# 5.0 In A Nutshell", BookCategory = BookCategory.IT });  
  13.       
  14.     //lets count if there are 3 elements/items inside the stack  
  15.     Assert.True(stackOfBooks_Csharp.Count == 3);  
  16. }  
Iterate through the stack collections. 
  1. [Fact]  
  2. public void Test_AddValues_To_Stack_And_Iterate_Through_NonGeneric()  
  3. {  
  4.     //create a new instance of stack   
  5.     Stack stackOfBooks_Csharp = new Stack();  
  6.   
  7.     //lets push some books at the stack  
  8.     stackOfBooks_Csharp.Push("C# in Depth");  
  9.     stackOfBooks_Csharp.Push("Pro C# 7");  
  10.     stackOfBooks_Csharp.Push("C# 5.0 In A Nutshell");  
  11.   
  12.     //lets iterate   
  13.     foreach (var item in stackOfBooks_Csharp)  
  14.     {  
  15.         Console.WriteLine(item);  
  16.   
  17.         Assert.Contains("C#", item.ToString());  
  18.     }  
  19. }  
  1. [Fact]  
  2. public void Test_AddValues_To_Stack_And_Iterate_Through_Generic()  
  3. {  
  4.     //create a new instance of stack   
  5.     Stack<Book> stackOfBooks_Csharp = new Stack<Book>();  
  6.   
  7.     //lets push some books at the stack  
  8.     stackOfBooks_Csharp.Push(new Book { Id =1, Title = "C# in Depth", BookCategory = BookCategory.IT });  
  9.     stackOfBooks_Csharp.Push(new Book { Id =2, Title = "Pro C# 7", BookCategory = BookCategory.IT });  
  10.     stackOfBooks_Csharp.Push(new Book { Id =3, Title = "C# 5.0 In A Nutshell", BookCategory = BookCategory.IT });  
  11.   
  12.     //lets iterate   
  13.     foreach (var item in stackOfBooks_Csharp)  
  14.     {  
  15.         Console.WriteLine(item);  
  16.   
  17.         Assert.Contains("C#", item.ToString());  
  18.     }  
  19. }  
Get the topmost item of the stack collection. 
  1. [Fact]  
  2. public void Test_AddValues_To_Stack_And_Get_The_Top_Most_NonGeneric()  
  3. {  
  4.     //create a new instance of stack   
  5.     Stack stackOfBooks_Csharp = new Stack();  
  6.   
  7.     //lets push some books at the stack  
  8.     stackOfBooks_Csharp.Push("C# in Depth");  
  9.     stackOfBooks_Csharp.Push("Pro C# 7");  
  10.     stackOfBooks_Csharp.Push("C# 5.0 In A Nutshell");  
  11.   
  12.     //lets get the top most item in the stack collection  
  13.     object topMost = stackOfBooks_Csharp.Peek();  
  14.     string topMostInString = topMost.ToString();   
  15.   
  16.     Assert.True(topMostInString.ToUpper() == "C# 5.0 IN A NUTSHELL");  
  17. }  
  1. [Fact]  
  2. public void Test_AddValues_To_Stack_And_Get_The_Top_Most_Generic()  
  3. {  
  4.     //create a new instance of stack   
  5.     Stack<Book> stackOfBooks_Csharp = new Stack<Book>();  
  6.   
  7.     //lets push some books at the stack  
  8.     stackOfBooks_Csharp.Push(new Book { Id =1,Title = "C# in Depth", BookCategory = BookCategory.IT });  
  9.     stackOfBooks_Csharp.Push(new Book { Id =2, Title = "Pro C# 7", BookCategory = BookCategory.IT });  
  10.     stackOfBooks_Csharp.Push(new Book { Id =3, Title = "C# 5.0 In A Nutshell", BookCategory = BookCategory.IT });  
  11.   
  12.     //lets get the top most item in the stack collection  
  13.     Book topMost = stackOfBooks_Csharp.Peek();  
  14.     string topMostInString = topMost.ToString();  
  15.       
  16.     Assert.True(topMostInString.ToUpper() == "C# 5.0 IN A NUTSHELL");  
  17. }  
Remove items in the stack collection. 
  1. [Fact]  
  2. public void Test_AddValue_To_Stack_And_Iterate_Then_Remove_Using_Pop_NonGeneric()  
  3. {  
  4.     //create a new instance of stack   
  5.     Stack stackOfBooks_Csharp = new Stack();  
  6.   
  7.     //lets push some books at the stack  
  8.     stackOfBooks_Csharp.Push("C# in Depth");  
  9.     stackOfBooks_Csharp.Push("Pro C# 7");  
  10.     stackOfBooks_Csharp.Push("C# 5.0 In A Nutshell");  
  11.   
  12.     while (stackOfBooks_Csharp.Count > 0)  
  13.     {  
  14.         //remove the item and returns the item  
  15.         object topMost = stackOfBooks_Csharp.Pop();  
  16.           
  17.         //topmost that was removed  
  18.         string topMostInString = topMost.ToString();  
  19.   
  20.         Assert.True(stackOfBooks_Csharp.Count >= 0);  
  21.     }  
  22.   
  23.     //expecting to have an empty stack collection  
  24.     Assert.True(stackOfBooks_Csharp.Count == 0);  
  25. }  
  1. [Fact]  
  2. public void Test_AddValue_To_Stack_And_Iterate_Then_Remove_Using_Pop_Generic()  
  3. {  
  4.     //create a new instance of stack   
  5.     Stack<Book> stackOfBooks_Csharp = new Stack<Book>();  
  6.   
  7.     //lets push some books at the stack  
  8.     stackOfBooks_Csharp.Push(new Book { Id =1, Title = "C# in Depth", BookCategory = BookCategory.IT });  
  9.     stackOfBooks_Csharp.Push(new Book { Id =2, Title = "Pro C# 7", BookCategory = BookCategory.IT });  
  10.     stackOfBooks_Csharp.Push(new Book { Id =3, Title = "C# 5.0 In A Nutshell", BookCategory = BookCategory.IT });  
  11.   
  12.     while (stackOfBooks_Csharp.Count > 0)  
  13.     {  
  14.         //remove the item and returns the item  
  15.         Book topMost = stackOfBooks_Csharp.Pop();  
  16.   
  17.         //topmost that was removed  
  18.         string topMostInString = topMost.ToString();  
  19.   
  20.         Assert.True(stackOfBooks_Csharp.Count >= 0);  
  21.     }  
  22.   
  23.     //expecting to have an empty stack collection  
  24.     Assert.True(stackOfBooks_Csharp.Count == 0);  
  25. }  
Clear the stack collection 
  1. [Fact]  
  2. public void Test_AddValue_To_Stack_And_Clear_Items_NonGeneric()  
  3. {  
  4.     //create a new instance of stack   
  5.     Stack stackOfBooks_Csharp = new Stack();  
  6.   
  7.     Assert.NotNull(stackOfBooks_Csharp);  
  8.   
  9.     //lets push some books at the stack  
  10.     stackOfBooks_Csharp.Push("C# in Depth");  
  11.     stackOfBooks_Csharp.Push("Pro C# 7");  
  12.     stackOfBooks_Csharp.Push("C# 5.0 In A Nutshell");  
  13.   
  14.     Assert.True(stackOfBooks_Csharp.Count > 0);  
  15.   
  16.     //clear or remove all the items in the stack collection  
  17.     stackOfBooks_Csharp.Clear();  
  18.   
  19.     Assert.True(stackOfBooks_Csharp.Count == 0);  
  20. }  
  1. [Fact]  
  2. public void Test_AddValue_To_Stack_And_Clear_Items_Generic()  
  3. {  
  4.     //create a new instance of stack   
  5.     Stack<Book> stackOfBooks_Csharp = new Stack<Book>();  
  6.   
  7.     Assert.NotNull(stackOfBooks_Csharp);  
  8.   
  9.     //lets push some books at the stack  
  10.     stackOfBooks_Csharp.Push(new Book { Title = "C# in Depth", BookCategory = BookCategory.IT });  
  11.     stackOfBooks_Csharp.Push(new Book { Title = "Pro C# 7", BookCategory = BookCategory.IT });  
  12.     stackOfBooks_Csharp.Push(new Book { Title = "C# 5.0 In A Nutshell", BookCategory = BookCategory.IT });  
  13.   
  14.     Assert.True(stackOfBooks_Csharp.Count > 0);  
  15.   
  16.     //clear or remove all the items in the stack collection  
  17.     stackOfBooks_Csharp.Clear();  
  18.   
  19.     Assert.True(stackOfBooks_Csharp.Count == 0);  
  20. }  
Check whether the stack collection contains a certain item. 
  1. [Fact]  
  2. public void Test_AddValue_To_Stack_And_Use_Contains_Method_NonGeneric()  
  3. {  
  4.     //create a new instance of stack   
  5.     Stack stackOfBooks_Csharp = new Stack();  
  6.   
  7.     Assert.NotNull(stackOfBooks_Csharp);  
  8.   
  9.     //lets push some books at the stack  
  10.     stackOfBooks_Csharp.Push("C# in Depth");  
  11.     stackOfBooks_Csharp.Push("Pro C# 7");  
  12.     stackOfBooks_Csharp.Push("C# 5.0 In A Nutshell");  
  13.   
  14.     //check whether it contains C# in Depth with the stack collection  
  15.     Assert.True(stackOfBooks_Csharp.Contains("C# in Depth"));  
  16.     Assert.False(stackOfBooks_Csharp.Contains("C#"));  
  17. }  
  1. [Fact]  
  2. public void Test_AddValue_To_Stack_And_Use_Contains_Method_Generic()  
  3. {  
  4.     //create a new instance of stack   
  5.     Stack<Book> stackOfBooks_Csharp = new Stack<Book>();  
  6.   
  7.     Assert.NotNull(stackOfBooks_Csharp);  
  8.   
  9.     //lets push some books at the stack  
  10.     stackOfBooks_Csharp.Push(new Book { Title = "C# in Depth", BookCategory = BookCategory.IT });  
  11.     stackOfBooks_Csharp.Push(new Book { Title = "Pro C# 7", BookCategory = BookCategory.IT });  
  12.     stackOfBooks_Csharp.Push(new Book { Title = "C# 5.0 In A Nutshell", BookCategory = BookCategory.IT });  
  13.   
  14.     var bookToCheck = new Book { Title = "C# in Depth", BookCategory = BookCategory.IT };  
  15.     var bookToCheck2 = new Book{ Title = "C# in Depth II", BookCategory = BookCategory.IT };  
  16.   
  17.     //check whether it contains C# in Depth with the stack collection  
  18.     Assert.True(stackOfBooks_Csharp.Contains(bookToCheck));  
  19.     Assert.False(stackOfBooks_Csharp.Contains(bookToCheck2));  
  20.   
  21.     Assert.Contains(stackOfBooks_Csharp, book => book.Title == "C# in Depth");  
  22.       
  23.     Assert.False(stackOfBooks_Csharp.Contains(bookToCheck2));  
  24. }  

Summary

 
In this article, we have discussed the following,
  • What is a Stack Collection?
  • What is the Difference between non-generic Stack to a generic Stack collection?
  • Create a new instance of Stack object generic and non-generic collection
  • Adding items to stack collection
  • Iterate through the stack collection
  • Get the topmost item of the stack collection
  • Remove items in the stack collection
  • Clear the stack collection
  • Check whether the stack collection contains a certain item
I hope you have enjoyed this article, as I have enjoyed it while writing. You can also find the sample code here at GitHub. Until next time, happy programming!