Home » C#.Net

Stack.Clone() method with example in C#

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

C# Stack.Clone() method

Stack.Clone() method is used to create a shallow copy of the stack.

Syntax:

    Object Stack.Clone();

Parameters: None

Return value: Object – a shallow copy of the stack.

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);

    creating clone/copy of the stack:
    Stack stk1 = (Stack)stk.Clone();
    
    Output:
    stk:  500 400 300 200 100
    stk1: 500 400 300 200 100

C# example to create a shallow copy of the stack using Stack.Clone() 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 (stk) elements are...");
            printStack(stk);

            //creating clone/copy of the stack
            Stack stk1 = (Stack)stk.Clone();

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


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

Output

Stack (stk) elements are...
500 400 300 200 100
Stack (stk1) elements are...
500 400 300 200 100

Reference: Stack.Clone Method



Comments and Discussions!

Load comments ↻





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