Stack<T> in C#
DevSniper
188 Views
Namespace :- System.Collections.Generic
Assembly :- System.Collections.dll
Signature :-
public class Stack<T> :
System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection
- Stack operates on the last-in-first-out (LIFO) principle.
- You should use Stack where you need to access the information/data in reverse order that it is stored.
- Stack can store duplicate elements.
- Stack is not Thread Safe.
Stack Constructors
- public Stack ();
- public Stack (System.Collections.Generic.IEnumerable<T> collection);
- public Stack (int capacity);
Stack Properties
- Count :- public int Count { get; }Gets the number of elements that are actually in the Stack<T>.
Creating and adding element in Stack<T>
using System; using System.Collections.Generic; class Program { static void Main() { var stack = new Stack<string>(); stack.Push("Python"); stack.Push("Java"); stack.Push("C#"); stack.Push("React"); stack.Push("C++"); Console.WriteLine("Peek element :- "+ stack.Peek()); Console.WriteLine("Pop :- "+ stack.Pop()); Console.WriteLine("After Pop, Peek element :- " + stack.Peek()); } }
Peek element :- C++ Pop :- C++ After Pop, Peek element :- React