Free Web Development Online Tutorials, Learn to Code
c# stack example Learn C# programming Language, stack in c#.net with example

Stack in C# Example

Stack LIFO style Collection

What is Stack in C#
Stack is a special type of collection in C#, which stores elements in LIFO style(Last In First Out). C# includes a generic and non-generic Stack. Here you will learn about the non-generic stack.

Stack allows duplicate values and also null value, Stack comes under System.Collections namespace

Important Stack Methods in C#

  • Peek

    Returns the top item from the stack.

  • Pop

    Removes and returns items from the top of the stack.

  • Contains

    Checks whether an item exists in the stack or not

  • Push

    Inserts an item at the top of the stack.

  • Clear

    Removes all items from the stack.

Stack push method example in C#

Push method allows adding object in stack object, so in example below we have created a new instance of stack object, and then added different type of values

Stack myStack = new Stack();
myStack.Push(1);
myStack.Push(1.10);
myStack.Push("this is a string");
myStack.Push(DateTime.Now);
myStack.Push(null);

retrive values from stack in C#

As you can see in above code we have created a stack object called “myStack”, then added few values using push method, now we retrieve those values by looping throw the collection.

foreach (var itm in myStack)                
{
Console.Write(itm);
}

Stack Peek Method Example in C#

Console.WriteLine(myStack.Peek());

Stack Pop Method Example in C#

The Pop() method removes and returns the value that was added last to the Stack.

Stack popStack = new Stack();
popStack.Push(1);
popStack.Push(2);
popStack.Push(3);
popStack.Push(4);
Console.Write("Total elements in Stack: {0}", popStack.Count);
while (myStack.Count > 0)
    Console.WriteLine(popStack.Pop());             
    Console.Write("Total elements in Stack: {0}", popStack.Count);

After executing the above code, the result would be

Total elements in Stack: 4

4
3
2
1

Total elements in Stack: 0

 

Learn Stack in C#
C# Tutorial
Other Online Tutorial

C# .net Interview Questions Answers