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


1 comment:

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

    ReplyDelete