C# | Creating a read-only wrapper for 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<T> 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.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating an List<T> of Integers
        List<int> mylist = new List<int>();
  
        // Adding elements to List
        mylist.Add(17);
        mylist.Add(19);
        mylist.Add(21);
        mylist.Add(9);
        mylist.Add(75);
        mylist.Add(19);
        mylist.Add(73);
  
        Console.WriteLine("Before Wrapping: ");
  
        // Displaying the elements
        // in the mylist
        foreach(int i in mylist)
        {
            Console.WriteLine(i);
        }
  
        // Creating a Read-Only packing
        // around the List
        IList<int> readlist = mylist.AsReadOnly();
  
        Console.WriteLine("After Wrapping: ");
  
        // Displaying the elements
        // of Read-Only Collection
        foreach(int j in readlist)
        {
            Console.WriteLine(j);
        }
          
        // You can add elements to
        // the original List i.e. mylist
        Console.WriteLine("Adding new element to mylist: ");
        mylist.Add(35);
          
        // Displaying the elements
        // in the mylist
        foreach(int k in mylist)
        {
            Console.WriteLine(k);
        }
  
        // But you cannot add elements
        // into the Read-Only Collection
        Console.WriteLine("Trying to add new element into readlist:");
  
        // it will give error
        readlist.Add(34);
          
    }
}

chevron_right


Output:

Before Wrapping: 
17
19
21
9
75
19
73
After Wrapping: 
17
19
21
9
75
19
73
Adding new element to mylist: 
17
19
21
9
75
19
73
35
Trying to add new element into readlist:

Runtime Error:

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

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.