C# Tutorial For Beginners: Working with collections(Stack)
Updated: Jan 19, 2022
It represents a last-in, first-out collection. It is used to create an array that supports the logic of last-in, first-out of elements. This article will provide code examples for its main properties and methods.
Note: the syntax of adding and removing items in the list, we will use the ‘push’ (add item) and ‘popping’ (remove item).
class Program
{
static void Main(string[] args)
{
//Creating a new stack
Stack StackLearning = new Stack();
//Adding elements
StackLearning.Push("st_1");
StackLearning.Push("st_2");
StackLearning.Push("st_3");
StackLearning.Push("st_4");
//Remove the top element in the stack
StackLearning.Pop();//will remove "st_4"
//Returns the object at the top of the Stack without removing it.
StackLearning.Pop();
//Determines whether an element is in the Stack.
Console.WriteLine(StackLearning.Contains("st_3"));//Returns True
//Remove all objects from the stack
StackLearning.Clear();
}
}