.Net Framework
C# Tutorial
C# Control Statement
C# Arrays
C# Object Class
C# Properties
C# Inheritance
C# Polymorphism
C# Abstraction
C# Strings
C# Exception Handling
C# File IO
C# Collections
C# Generics
C# Delegates
C# Reflection
Anonymous Function
C# Multithreading
C# Synchronization
C# Web Service
C# Misc
C# New Features
C# Programs
C# Interview Questions
ADO.NET Tutorial
ASP.NET Tutorial
C# Stack
C# Stack class is used to push and pop elements. It uses the concept of Stack that arranges elements in LIFO (Last In First Out) order. It can have duplicate elements. It is found in System.Collections.Generic namespace.
C# Stack example
Let's see an example of generic Stack class that stores elements using Push() method, removes elements using Pop() method and iterates elements using for-each loop.
using System;
using System.Collections.Generic;
public class StackExample
{
public static void Main(string[] args)
{
Stack names = new Stack();
names.Push("Anil");
names.Push("Sunil");
names.Push("Nikhil");
names.Push("Nitin");
foreach (string name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("Peek element: "+names.Peek());
Console.WriteLine("Pop: "+ names.Pop());
Console.WriteLine("After Pop, Peek element: " + names.Peek());
}
}
using System.Collections.Generic;
public class StackExample
{
public static void Main(string[] args)
{
Stack names = new Stack();
names.Push("Anil");
names.Push("Sunil");
names.Push("Nikhil");
names.Push("Nitin");
foreach (string name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("Peek element: "+names.Peek());
Console.WriteLine("Pop: "+ names.Pop());
Console.WriteLine("After Pop, Peek element: " + names.Peek());
}
}
Output:
Anil
Sunil
Nikhil
Nitin
Sunil
Nikhil
Nitin
Peek element: Nitin Pop: Nitin After Pop, Peek element: Nikhil