Creating a Read Only List using LINQ

Have you felt the need of creating a read only List<> ? LINQ makes it very simple with the AsReadOnly() method. Here's how


List<int> integ = new List<int>(){100,200,300,400,500};

IList<int> noModif = integ.AsReadOnly();

foreach (var i in noModif)


    // print i







catch(Exception ex)


    // Exception raised stating that this collection is read only




Dim integ As New List(Of Integer)(New Integer() {100, 200, 300, 400, 500})

Dim noModif As IList(Of Integer) = integ.AsReadOnly()

For Each i In noModif

' print i

Next i




Catch ex As Exception

' Exception raised stating that this collection is read only

End Try

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

1 comment:

Anonymous said...

This is not LINQ. Method AsReadOnly is defined on List<T>.