Lesson #22 - Working with collections(Stack)

It represents a last-in, first-out collection. It is used when you need to create an array that supports the logic of last-in, first-out of elements. In this article, I 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();

}

}




1 view0 comments