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. namespace Stacks_Non_Generic_And_Generic_Csharp_101.Model
  4. {
  5. public enum BookCategory
  6. {
  7. IT = 0,
  8. CRIME = 1,
  9. SPORTS = 2
  10. }
  11. public class Book : IEquatable<Book>
  12. {
  13. public int Id { get; set; }
  14. public string Title { get; set; }
  15. public BookCategory BookCategory { get; set; }
  16. public bool Equals([AllowNull] Book other)
  17. {
  18. return this.Title == other.Title;
  19. }
  20. public override string ToString()
  21. {
  22. return this.Title;
  23. }
  24. }
  25. }
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. //checks whether the declared stackofBooks is not null
  7. Assert.NotNull(stackofBooks);
  8. //checks whether the stackofBooks collection count is zero
  9. //because we haven't added anyting yet
  10. Assert.True(stackofBooks.Count == 0);
  11. //create a new instance of string collection of books and initialize it
  12. string[] books = new string[] { "C# in Depth", "Pro C# 7", "C# 5.0 In A Nutshell" };
  13. //create a new instance of stack and pass the book collection
  14. Stack stackOfBooks_Csharp = new Stack(books);
  15. //checks whether the declared stackofBooks is not null
  16. Assert.NotNull(stackOfBooks_Csharp);
  17. //checks whether the stackOfBooks collection count is greater than zero
  18. Assert.True(stackOfBooks_Csharp.Count > 0);
  19. }
  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. //checks whether the declared stackofBooks is not null
  7. Assert.NotNull(stackofBooks);
  8. //checks whether the stackofBooks collection count is zero
  9. //because we haven't added anyting yet
  10. Assert.True(stackofBooks.Count == 0);
  11. //create a new instance of book collection and initialize it
  12. var books = new Book[] {
  13. new Book { Id =1, Title = "C# in Depth", BookCategory = BookCategory.IT } ,
  14. new Book { Id =2, Title = "Pro C# 7" , BookCategory = BookCategory.IT },
  15. new Book { Id =3, Title = "C# 5.0 In A Nutshell", BookCategory = BookCategory.IT } };
  16. //create a new instance of generic stack and pass the book collection
  17. Stack<Book> stackOfBooks_Csharp = new Stack<Book>(books);
  18. //checks whether the declared stackofBooks is not null
  19. Assert.NotNull(stackOfBooks_Csharp);
  20. //checks whether the stackOfBooks collection count is greater than zero
  21. Assert.True(stackOfBooks_Csharp.Count > 0);
  22. }
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. //lets push some books at the stack
  9. stackOfBooks_Csharp.Push("C# in Depth");
  10. stackOfBooks_Csharp.Push("Pro C# 7");
  11. stackOfBooks_Csharp.Push("C# 5.0 In A Nutshell");
  12. //lets count if there are 3 elements/items inside the stack
  13. Assert.True(stackOfBooks_Csharp.Count == 3);
  14. }
  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. //lets push some books at the stack
  9. stackOfBooks_Csharp.Push(new Book { Id = 1, Title = "C# in Depth", BookCategory = BookCategory.IT });
  10. stackOfBooks_Csharp.Push(new Book { Id = 2, Title = "Pro C# 7", BookCategory = BookCategory.IT });
  11. stackOfBooks_Csharp.Push(new Book { Id = 3, Title = "C# 5.0 In A Nutshell", BookCategory = BookCategory.IT });
  12. //lets count if there are 3 elements/items inside the stack
  13. Assert.True(stackOfBooks_Csharp.Count == 3);
  14. }
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. //lets push some books at the stack
  7. stackOfBooks_Csharp.Push("C# in Depth");
  8. stackOfBooks_Csharp.Push("Pro C# 7");
  9. stackOfBooks_Csharp.Push("C# 5.0 In A Nutshell");
  10. //lets iterate
  11. foreach (var item in stackOfBooks_Csharp)
  12. {
  13. Console.WriteLine(item);
  14. Assert.Contains("C#", item.ToString());
  15. }
  16. }
  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. //lets push some books at the stack
  7. stackOfBooks_Csharp.Push(new Book { Id =1, Title = "C# in Depth", BookCategory = BookCategory.IT });
  8. stackOfBooks_Csharp.Push(new Book { Id =2, Title = "Pro C# 7", BookCategory = BookCategory.IT });
  9. stackOfBooks_Csharp.Push(new Book { Id =3, Title = "C# 5.0 In A Nutshell", BookCategory = BookCategory.IT });
  10. //lets iterate
  11. foreach (var item in stackOfBooks_Csharp)
  12. {
  13. Console.WriteLine(item);
  14. Assert.Contains("C#", item.ToString());
  15. }
  16. }
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. //lets push some books at the stack
  7. stackOfBooks_Csharp.Push("C# in Depth");
  8. stackOfBooks_Csharp.Push("Pro C# 7");
  9. stackOfBooks_Csharp.Push("C# 5.0 In A Nutshell");
  10. //lets get the top most item in the stack collection
  11. object topMost = stackOfBooks_Csharp.Peek();
  12. string topMostInString = topMost.ToString();
  13. Assert.True(topMostInString.ToUpper() == "C# 5.0 IN A NUTSHELL");
  14. }
  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. //lets push some books at the stack
  7. stackOfBooks_Csharp.Push(new Book { Id =1,Title = "C# in Depth", BookCategory = BookCategory.IT });
  8. stackOfBooks_Csharp.Push(new Book { Id =2, Title = "Pro C# 7", BookCategory = BookCategory.IT });
  9. stackOfBooks_Csharp.Push(new Book { Id =3, Title = "C# 5.0 In A Nutshell", BookCategory = BookCategory.IT });
  10. //lets get the top most item in the stack collection
  11. Book topMost = stackOfBooks_Csharp.Peek();
  12. string topMostInString = topMost.ToString();
  13. Assert.True(topMostInString.ToUpper() == "C# 5.0 IN A NUTSHELL");
  14. }
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. //lets push some books at the stack
  7. stackOfBooks_Csharp.Push("C# in Depth");
  8. stackOfBooks_Csharp.Push("Pro C# 7");
  9. stackOfBooks_Csharp.Push("C# 5.0 In A Nutshell");
  10. while (stackOfBooks_Csharp.Count > 0)
  11. {
  12. //remove the item and returns the item
  13. object topMost = stackOfBooks_Csharp.Pop();
  14. //topmost that was removed
  15. string topMostInString = topMost.ToString();
  16. Assert.True(stackOfBooks_Csharp.Count >= 0);
  17. }
  18. //expecting to have an empty stack collection
  19. Assert.True(stackOfBooks_Csharp.Count == 0);
  20. }
  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. //lets push some books at the stack
  7. stackOfBooks_Csharp.Push(new Book { Id =1, Title = "C# in Depth", BookCategory = BookCategory.IT });
  8. stackOfBooks_Csharp.Push(new Book { Id =2, Title = "Pro C# 7", BookCategory = BookCategory.IT });
  9. stackOfBooks_Csharp.Push(new Book { Id =3, Title = "C# 5.0 In A Nutshell", BookCategory = BookCategory.IT });
  10. while (stackOfBooks_Csharp.Count > 0)
  11. {
  12. //remove the item and returns the item
  13. Book topMost = stackOfBooks_Csharp.Pop();
  14. //topmost that was removed
  15. string topMostInString = topMost.ToString();
  16. Assert.True(stackOfBooks_Csharp.Count >= 0);
  17. }
  18. //expecting to have an empty stack collection
  19. Assert.True(stackOfBooks_Csharp.Count == 0);
  20. }
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. Assert.NotNull(stackOfBooks_Csharp);
  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. Assert.True(stackOfBooks_Csharp.Count > 0);
  12. //clear or remove all the items in the stack collection
  13. stackOfBooks_Csharp.Clear();
  14. Assert.True(stackOfBooks_Csharp.Count == 0);
  15. }
  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. Assert.NotNull(stackOfBooks_Csharp);
  7. //lets push some books at the stack
  8. stackOfBooks_Csharp.Push(new Book { Title = "C# in Depth", BookCategory = BookCategory.IT });
  9. stackOfBooks_Csharp.Push(new Book { Title = "Pro C# 7", BookCategory = BookCategory.IT });
  10. stackOfBooks_Csharp.Push(new Book { Title = "C# 5.0 In A Nutshell", BookCategory = BookCategory.IT });
  11. Assert.True(stackOfBooks_Csharp.Count > 0);
  12. //clear or remove all the items in the stack collection
  13. stackOfBooks_Csharp.Clear();
  14. Assert.True(stackOfBooks_Csharp.Count == 0);
  15. }
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. Assert.NotNull(stackOfBooks_Csharp);
  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. //check whether it contains C# in Depth with the stack collection
  12. Assert.True(stackOfBooks_Csharp.Contains("C# in Depth"));
  13. Assert.False(stackOfBooks_Csharp.Contains("C#"));
  14. }
  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. Assert.NotNull(stackOfBooks_Csharp);
  7. //lets push some books at the stack
  8. stackOfBooks_Csharp.Push(new Book { Title = "C# in Depth", BookCategory = BookCategory.IT });
  9. stackOfBooks_Csharp.Push(new Book { Title = "Pro C# 7", BookCategory = BookCategory.IT });
  10. stackOfBooks_Csharp.Push(new Book { Title = "C# 5.0 In A Nutshell", BookCategory = BookCategory.IT });
  11. var bookToCheck = new Book { Title = "C# in Depth", BookCategory = BookCategory.IT };
  12. var bookToCheck2 = new Book{ Title = "C# in Depth II", BookCategory = BookCategory.IT };
  13. //check whether it contains C# in Depth with the stack collection
  14. Assert.True(stackOfBooks_Csharp.Contains(bookToCheck));
  15. Assert.False(stackOfBooks_Csharp.Contains(bookToCheck2));
  16. Assert.Contains(stackOfBooks_Csharp, book => book.Title == "C# in Depth");
  17. Assert.False(stackOfBooks_Csharp.Contains(bookToCheck2));
  18. }

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!