C# | Creating a read-only wrapper for the List

List<T>.AsReadOnly Method is used to get a read-only ReadOnlyCollection<T> wrapper for the current collection.

Syntax:

public System.Collections.ObjectModel.ReadOnlyCollection AsReadOnly ();

Return Value: It returns an object that acts as a read-only wrapper around the current List<T>.

Example:



filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to create a read-only
// wrapper for the List<T>
using System;
using System.Collections;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating an List<T> of Integers
        List<int> firstlist = new List<int>();
  
        // Adding elements to List
        firstlist.Add(1);
        firstlist.Add(2);
        firstlist.Add(3);
        firstlist.Add(4);
        firstlist.Add(5);
        firstlist.Add(6);
        firstlist.Add(7);
  
        Console.WriteLine("Before Wrapping: ");
  
        // Displaying the elements in the List
        foreach(int i in firstlist)
        {
            Console.WriteLine(i);
        }
  
        // Creating a Read-Only packing
        // around the List<T>
        IList<int> mylist2 = firstlist.AsReadOnly();
  
        Console.WriteLine("After Wrapping: ");
  
        // Displaying the elements
        foreach(int m in mylist2)
        {
            Console.WriteLine(m);
        }
  
        Console.WriteLine("Trying to add new element into mylist2:");
  
        // it will give error
        mylist2.Add(8);
    }
}

chevron_right


Output:

Before Wrapping: 
1
2
3
4
5
6
7
After Wrapping: 
1
2
3
4
5
6
7
Trying to add new element into mylist2:

Runtime Error:

Unhandled Exception:
System.NotSupportedException: Collection is read-only.

Note:

  • A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection. If changes are made to the underlying collection, the read-only collection reflects those changes.
  • This method is an O(1) operation.

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.