27 Mar

C# Stack Example

The stack represents a simple last-in-first-out (LIFO) non-generic collection of objects.

  • To add an element to the stack, the push method is used. The statement’s general syntax is shown below:
stack.Push("Obj");
  • To remove an element from the stack, the pop method is used. The pop operation returns the stack’s top element. The statement’s general syntax is given below:
object popObj = stack.Pop();

Stack Example:

            Stack stack = new Stack();
            stack.Push("Obj1");
            stack.Push("Obj2");
            stack.Push("Obj3");

            Console.WriteLine("Objects");
            Console.WriteLine("-------");
            foreach (Object obj in stack)
            {
                Console.WriteLine(obj);
            }
            object popObj = stack.Pop();
            Console.WriteLine("Last In/First Out(LIFO): " + popObj);

            Console.WriteLine("The number of elements in the stack: " + stack.Count);
            Console.WriteLine("Contains Obj1:  " + stack.Contains("Obj1"));

Program Output:

stack output