C# Programming Language: Stack

Creating The Stack

using System.Collections.Generic;
Stack<int> myStack = new Stack<int>();

Adding Elements to The Stack

Stack<int> myStack = new Stack<int>();
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
Console.WriteLine(String.Join(" ", myStack));
Output:
3 2 1

Accessing The Top Element of The Stack

Stack<int> myStack = new Stack<int>();
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
Console.WriteLine(myStack.Peek());
Output:
3

Removing The Top Element of The Stack

Stack<int> myStack = new Stack<int>();
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
Console.WriteLine(myStack.Pop());
Console.WriteLine(String.Join(" ", myStack));
Output:
3
2 1

Clearing Out The Stack

Stack<int> myStack = new Stack<int>();
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
myStack.Clear();
Console.WriteLine(String.Join(" ", myStack));
Output:

Checking Elements in a Stack

Stack<int> myStack = new Stack<int>();
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
Console.WriteLine(myStack.Contains(2));
Console.WriteLine(myStack.Contains(4));
Output:
True
False

Checking The Size of a Stack

Stack<int> myStack = new Stack<int>();
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
Console.WriteLine(myStack.Count);
Output:
3

Conclusion

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

⚙️ Task 7.1 -

GSoC’21 — Week 7 and 8 — Setting up the reply functionality

How to install a coding environment on your Steam Deck

Online Studies with WeStudy

How to choose a software development company?

Open API Content Validation Issue on WSO2 APIM

PowerShell Code Signing

The Process Automation Map

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jesse L

Jesse L

More from Medium

C# Value Types and Reference Types

Into Image

C# Simple Interfaces: Service

C# Programming — Variables (Lesson 01)

1.2 Evolution of C#