Stack serves as a collection of elements. There are two main operations of Stack.
Push - Adds elements to the collection.
Pop - Removes elements from the collection.
Stack works in a LIFO (Last in, First Out) manner. It is considered a linear data structure. The push and pop operations occur only at one end of the structure.
Stack Class in C#
We have Stack class in C#. It represents a simple last-in-first-out (LIFO) non-generic collection of objects.
Namespace:
System.Collections
Assemblies
System.Collections.NonGeneric.dll, mscorlib.dll, netstandard.dll.
Stack<T> Class (Generic Version)
Namespace:
System.Collections.Generic
Assemblies:
System.Collections.dll, System.dll, netstandard.dll
Example- Reverse a string using Stack
Code
  1. using System;
  2. using System.Collections.Generic;
  3. namespace ReverseAStringUsingStack
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. Console.WriteLine("Enter a String:");
  10. string sInput = Console.ReadLine();
  11. string sOutput = ReverseAString(sInput);
  12. Console.WriteLine("\n Reversed String is: " + sOutput);
  13. Console.Read();
  14. }
  15. private static string ReverseAString(string sInput)
  16. {
  17. Stack<char> objStack = new Stack<char>();
  18. string sOutPut = string.Empty;
  19. if (sInput != null)
  20. {
  21. int iInputLength = sInput.Length;
  22. for (int i=0;i<iInputLength;i++)
  23. {
  24. objStack.Push(sInput[i]);
  25. }
  26. while (objStack.Count != 0)
  27. {
  28. sOutPut += objStack.Pop();
  29. }
  30. }
  31. return sOutPut;
  32. }
  33. }
  34. }
Output