Stack.Contains() method with example in C#

C# Stack.Contains() strategy: Here, we will find out about the Contains() technique for Stack class in C#.

C# Stack.Contains() strategy

Stack.Contains() strategy is utilized to check whether a component/object exists in the stack or not, it returns genuine if an article/component exists in the stack else it returns false.

Syntax:

    bool Stack.Clone(Object);

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

Return value: bool – returns genuine if the object exists in the stack else returns bogus.

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 article/component exists in the stack or not utilizing Stack.Contains() technique

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

Leave a Comment

error: Alert: Content is protected!!