Creating a read-only wrapper for the ArrayList in C#


To create a read-only wrapper for ArrayList, the code is as follows −

Example

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      ArrayList list = new ArrayList();
      list.Add("One");
      list.Add("Two");
      list.Add("Three");
      list.Add("Four");
      list.Add("Five");
      list.Add("Six");
      list.Add("Seven");
      list.Add("Eight");
      Console.WriteLine("ArrayList elements...");
      foreach(string str in list){
         Console.WriteLine(str);
      }
      Console.WriteLine("ArrayList is read-only? = "+list.IsReadOnly);
   }
}

Output

This will produce the following output −

ArrayList elements...
One
Two
Three
Four
Five
Six
Seven
Eight
ArrayList is read-only? = False

Example

Let us now see another example −

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      ArrayList list = new ArrayList();
      list.Add("One");
      list.Add("Two");
      list.Add("Three");
      list.Add("Four");
      list.Add("Five");
      list.Add("Six");
      list.Add("Seven");
      list.Add("Eight");
      Console.WriteLine("ArrayList elements...");
      foreach(string str in list){
         Console.WriteLine(str);
      }
      Console.WriteLine("ArrayList is read-only? = "+list.IsReadOnly);
      ArrayList list2 = ArrayList.ReadOnly(list);
      Console.WriteLine("ArrayList is read-only now? = "+list2.IsReadOnly);
   }
}

Output

This will produce the following output −

ArrayList elements...
One
Two
Three
Four
Five
Six
Seven
Eight
ArrayList is read-only? = False ArrayList is read-only now? = True

Updated on: 05-Dec-2019

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements