C# | Creating a read-only wrapper for List
Last Updated :
27 Jan, 2019
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:
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
List< int > mylist = new List< int >();
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: " );
foreach ( int i in mylist)
{
Console.WriteLine(i);
}
IList< int > readlist = mylist.AsReadOnly();
Console.WriteLine( "After Wrapping: " );
foreach ( int j in readlist)
{
Console.WriteLine(j);
}
Console.WriteLine( "Adding new element to mylist: " );
mylist.Add(35);
foreach ( int k in mylist)
{
Console.WriteLine(k);
}
Console.WriteLine( "Trying to add new element into readlist:" );
readlist.Add(34);
}
}
|
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:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...