Creating a synchronized wrapper for the ArrayList in C#


To create a synchronized wrapper for the ArrayList, the code is as follows −

Example

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main() {
      ArrayList arrList = new ArrayList();
      arrList.Add("AB");
      arrList.Add("CD");
      arrList.Add("EF");
      arrList.Add("GH");
      arrList.Add("IJ");
      arrList.Add("KL");
      Console.WriteLine("ArrayList elements...");
      foreach(string str in arrList) {
         Console.WriteLine(str);
      }
      Console.WriteLine("ArrayList is synchronized? = "+arrList.IsSynchronized);
   }
}

Output

This will produce the following output −

ArrayList elements...
AB
CD
EF
GH
IJ
KL
ArrayList is synchronized? = False

Example

Let us see another example −

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main() {
      ArrayList arrList = new ArrayList();
      arrList.Add("AB");
      arrList.Add("CD");
      arrList.Add("EF");
      arrList.Add("GH");
      arrList.Add("IJ");
      arrList.Add("KL");
      Console.WriteLine("ArrayList elements...");
      foreach(string str in arrList) {
         Console.WriteLine(str);
      }
      Console.WriteLine("ArrayList is synchronized? = "+arrList.IsSynchronized);
      ArrayList arrList2 = ArrayList.Synchronized(arrList);
      Console.WriteLine("ArrayList is synchronized? = "+arrList2.IsSynchronized);
   }
}

Output

This will produce the following output −

ArrayList elements...
AB
CD
EF
GH
IJ
KL
ArrayList is synchronized? = False
ArrayList is synchronized? = True

Updated on: 06-Dec-2019

65 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements