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:
// 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:
Recommended Posts:
- Difference between Method Overriding and Method Hiding in C#
- C# | String.Contains() Method
- C# | Math.Max() Method
- Decimal.Add() Method in C#
- C# | Math.Min() Method
- Stack.Pop() Method in C#
- DateTimeOffset.Add() Method in C#
- Extension Method in C#
- Stack.Contains() Method in C#
- C# | CopyTo() Method
- C# | Trim() Method
- C# | Method Parameters
- C# | Remove() Method
- C# | IndexOfAny() Method
- Queue.Contains() Method in C#
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.



