Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Returning read-only collection

By , 31 May 2011
Rate this:
Please Sign up or sign in to vote.

Another good idea is to return the list as enumerable using:

return m_privateCollection.AsEnumerable();

Now what are the differences?

  1. AsReadOnly() creates a completely new collection of list. Depending on the count of items and where the resource is, this may take a long time.
  2. AsEnumerable() returns exactly the items stored on the list, but one by one (probably using yield). Therefore adding and removing the items are not meaningful actions.
  3. AsEnumerable() is lazy load. It means that AsEnumerable() won't query the items until the time you want to encounter the items. But methods like AsList() and AsReadOnly() create the list exactly at the time you call them.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Mohammad Mir mostafa
Program Manager
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
No Biography provided

Comments and Discussions

GeneralReason for my vote of 1 Item 2 is also wrong. col.AsEnumerab... PinmemberJaroslav Kaas7-Jun-11 20:06 
GeneralReason for my vote of 2 Item 1 is absolutely wrong. Pinmembericetea943-Jun-11 3:18 
GeneralAt least for List<t>, AsReadOnly() returns a wrapper around ... Pinmembericetea943-Jun-11 3:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 31 May 2011
Article Copyright 2011 by Mohammad Mir mostafa
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid