Click here to Skip to main content
15,883,705 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Returning read-only collection

Rate me:
Please Sign up or sign in to vote.
3.60/5 (5 votes)
31 May 2011CPOL 8.9K   1   3
Another good idea is to return the list as enumerable using:return m_privateCollection.AsEnumerable();Now what are the differences?AsReadOnly() creates a completely new collection of list. Depending on the count of items and where the resource is, this may take a long...

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


C#
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.

License

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


Written By
Architect Iran
Iran (Islamic Republic of) Iran (Islamic Republic of)
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

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

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

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