Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Returning read-only collection

3.60/5 (5 votes)
31 May 2011CPOL 9.6K  
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)