C# Stack.Clone() strategy: Here, we will find out about the Clone() technique for Stack class in C#.
C# Stack.Clone() strategy
Stack.Clone() strategy is utilized to make a shallow duplicate of the stack.
Syntax:
Object Stack.Clone();
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 make a shallow duplicate of the stack utilizing Stack.Clone() strategy
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