C# Stack Class

C# Stack Class

The Stack class in C# represents a last-in, first-out (LIFO) collection of objects. It is a part of the System.Collections namespace. A generic version, Stack<T>, is also available in the System.Collections.Generic namespace, which offers type safety and is generally recommended over the non-generic version.

Let's explore a tutorial on how to use the Stack class in C#:

1. Setting Up

For the generic version of Stack:

using System.Collections.Generic; 

For the non-generic version:

using System.Collections; 

2. Creating a Stack

Generic Version:

Stack<int> numbers = new Stack<int>(); 

Non-Generic Version:

Stack numbers = new Stack(); 

3. Pushing Items onto the Stack

To add an item to the top of the stack, use the Push method:

numbers.Push(1); numbers.Push(2); numbers.Push(3); 

4. Popping Items off the Stack

To remove and return the item at the top of the stack, use the Pop method:

int poppedNumber = numbers.Pop(); // poppedNumber will be 3 

5. Peeking at the Top

To see the item at the top of the stack without removing it, use the Peek method:

int topNumber = numbers.Peek(); // topNumber will be 2 

6. Checking If Stack Contains an Item

bool containsTwo = numbers.Contains(2); // containsTwo will be true 

7. Counting Items

To get the number of items in the stack, use the Count property:

int count = numbers.Count; // count will be 2 (since we've popped one item) 

8. Clearing the Stack

To remove all items from the stack:

numbers.Clear(); 

9. Iterating Through a Stack

You can use a foreach loop to iterate through the items, which will be accessed in LIFO order:

foreach (int number in numbers) { Console.WriteLine(number); } 

10. Points to Remember:

  1. LIFO Principle: Remember, Stack works on the LIFO principle. The last item you add (push) is the first item you remove (pop).

  2. Underflow Exception: If you try to Pop or Peek on an empty stack, a InvalidOperationException will be thrown. Always check if the stack is empty using the Count property before performing these operations.

  3. Type Safety with Generics: The generic version (Stack<T>) ensures type safety, so it's recommended to use it over the non-generic version.

Conclusion

The Stack class provides a simple and effective data structure for scenarios where LIFO access is required. It's commonly used in algorithms, function call implementations, undo-redo functionality, and more. Always remember to handle potential exceptions when using stack operations on possibly empty stacks.


More Tags

webpacker range-checking textkit coupon azure-virtual-machine fasterxml assertion centos common-table-expression browser-detection

More Programming Guides

Other Guides

More Programming Examples