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

C#


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


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


foreach (var i in noModif)


{


    // print i


}


 


try


{


    noModif.Add(600);


}


catch(Exception ex)


{


    // Exception raised stating that this collection is read only


}




VB.NET


 


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


 


Try


    noModif.Add(600)


Catch ex As Exception


' Exception raised stating that this collection is read only


End Try







About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 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>.