Stack represents a last-in, first out collection of object.
Stack<T>.Contains(Object) Method is used to check whether an element is in the Stack<T> or not.
Syntax:
public virtual bool Contains(object obj);
Return Value: The function returns True if the element exists in the Stack<T> and returns False if the element doesn’t exist in the Stack.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to Check if a Stack // contains an element using System; using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of strings Stack<string> myStack = new Stack<string>(); // Inserting the elements into the Stack myStack.Push("Geeks"); myStack.Push("Geeks Classes"); myStack.Push("Noida"); myStack.Push("Data Structures"); myStack.Push("GeeksforGeeks"); // Checking whether the element is // present in the Stack or not // The function returns True if the // element is present in the Stack, else // returns False Console.WriteLine(myStack.Contains("GeeksforGeeks")); } } |
True
Example 2:
// C# code to Check if a Stack // contains an element using System; using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of Integers Stack<int> myStack = new Stack<int>(); // Inserting the elements into the Stack myStack.Push(5); myStack.Push(10); myStack.Push(15); myStack.Push(20); myStack.Push(25); // Checking whether the element is // present in the Stack or not // The function returns True if the // element is present in the Stack, else // returns False Console.WriteLine(myStack.Contains(7)); } } |
False
Reference:
Recommended Posts:
- C# | Check if an element is in the Queue
- C# | Check if a HashSet contains the specified element
- C# | How to check whether a List contains a specified element
- C# | Check if an element is in the Collection<T>
- C# | Check if the SortedSet contains a specific element
- C# | Check whether an element is contained in the ArrayList
- C# | Check if every List element matches the predicate conditions
- C# Stack with Examples
- Implementing Stack in C#
- Stack.Contains() Method in C#
- Stack.Pop() Method in C#
- C# | Stack Class
- C# | How to create a Stack
- Stack.Peek Method in C#
- Removing the object from the top of the Stack in C#
- C# | Copy the Stack to an Array
- C# | Convert Stack to array
- Getting an enumerator that iterates through the Stack in C#
- Stack.Synchronized() Method in C#
- Stack.Equals() Method in C#
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

