Stack.Synchronized() Method in C#

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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");
    }
}

chevron_right


Output:

myStack is Not Synchronized.
st is Synchronized.

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Runtime Error:

Unhandled Exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: stack

Reference:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.