Home » C#.Net

Stack.Contains() method with example in C#

C# Stack.Contains() method: Here, we are going to learn about the Contains() method of Stack class in C#.
Submitted by IncludeHelp, on March 30, 2019

C# Stack.Contains() method

Stack.Contains() method is used to check whether an element/object exists in the stack or not, it returns true if an object/element exists in the stack else it returns false.

Syntax:

    bool Stack.Clone(Object);

Parameters: Object – to be checked, whether it exists in the stack or not.

Return value: bool – returns true if object exists in the stack else returns false.

Example:

    declare and initialize a stack:
    Stack stk = new Stack();

    insertting elements:
    stk.Push(100);
    stk.Push(200);
    stk.Push(300);
    stk.Push(400);
    stk.Push(500);

    checking elements:
    stk.Contains(100);
    stk.Contains(800);
    
    Output:
    true
    false   

C# example to check whether an object/element exists in the stack or not using Stack.Contains() method

using System;
using System.Text;
using System.Collections;

namespace Test
{
    class Program
    {
        //function to print stack elements
        static void printStack(Stack s)
        {
            foreach (Object obj in s)
            {
                Console.Write(obj + " ");
            }
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            //declare and initialize a stack
            Stack stk = new Stack();

            //insertting elements
            stk.Push(100);
            stk.Push(200);
            stk.Push(300);
            stk.Push(400);
            stk.Push(500);

            //printing stack elements
            Console.WriteLine("Stack elements are...");
            printStack(stk);

            //checking elements
            if (stk.Contains(100) == true)
                Console.WriteLine("100 exists in the stack");
            else
                Console.WriteLine("100 does not exist in the stack");

            if (stk.Contains(800) == true)
                Console.WriteLine("800 exists in the stack");
            else
                Console.WriteLine("800 does not exist in the stack");


            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

Stack elements are...
500 400 300 200 100
100 exists in the stack
800 does not exist in the stack

Reference: Stack.Contains(Object) Method



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.