In C#, Stack is collection where elements are Last In First Out (LIFO). That means Last entered element will be First Out. In general it looks like stack of dishes at a buffet table.
We can add element to Stack by using Push() method and we can pull element from Stack by using Pop() method. We can add and get element from Stack by using Push and Pop methods as shown below.
using System;
using System.Collections;
namespace StackExample
{
class Program
{
static void Main(string[] args)
{
Stack sCollection = new Stack();
//Add elemnts to Stack by using Push() method
sCollection.Push("A");
sCollection.Push("B");
sCollection.Push("C");
sCollection.Push("D");
//pop Last element by using Pop() method
Console.WriteLine(sCollection.Pop());
Console.ReadLine();
}
}
}
As shown above we are adding the elements to Stack by using Push() method. While pushing the elements, latest element placed on previous element. So whenever we are getting the element by using Pop() method last element will displays first.
Stack has CopyTo() and ToArray() methods to copy the Stack elements to One dimensional array.
tags:
C# LIFO, C# Stack, Stack pop, Stack push