This method(comes under System.Collections Namespace) is used to return a synchronized (thread safe) wrapper for the Stack. To guarantee the thread safety of the Stack, all operations must be done through this wrapper.
Syntax:
public static System.Collections.Stack Synchronized (System.Collections.Stack stack);
Return Value: It returns synchronized wrapper around the Stack.
Exception: This method will give ArgumentNullException if the stack is null.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# code to illustrate the // Stack.Synchronized() Method using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a Stack
Stack myStack = new Stack();
// Inserting the elements into the Stack
myStack.Push( "Geeks" );
myStack.Push( "Geeks Classes" );
myStack.Push( "Noida" );
myStack.Push( "Data Structures" );
myStack.Push( "GeeksforGeeks" );
// Creates a synchronized
// wrapper around the Stack
Stack st = Stack.Synchronized(myStack);
// Displays the synchronization
// status of both Stack
Console.WriteLine( "myStack is {0}." , myStack.IsSynchronized ?
"Synchronized" : "Not Synchronized" );
Console.WriteLine( "st is {0}." , st.IsSynchronized ?
"Synchronized" : "Not Synchronized" );
}
} |
Output:
myStack is Not Synchronized. st is Synchronized.
Example 2:
// C# code to illustrate the // Stack.Synchronized() Method using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a Stack
Stack myStack = new Stack();
// Inserting the elements into the Stack
myStack.Push( "C" );
myStack.Push( "C++" );
myStack.Push( "Java" );
myStack.Push( "C#" );
myStack.Push( "Python" );
// it will give error as
// the parameter is null
Stack sq = Stack.Synchronized( null );
}
} |
Runtime Error:
Unhandled Exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: stack
Reference: